簡體   English   中英

即使在容器溢出時也要保持元素居中

[英]Keep element centered even when overflowing its container

我在下面的代碼片段中重新創建了我的問題:如果你將它設為全頁並拖動以減小窗口的水平尺寸,當h1元素超出其容器的邊界時,它不會保持居中。

這是一個視覺:

在此輸入圖像描述

請注意,超過其容器邊界后,它仍然保持左對齊。 我希望它保持中心。 有一個簡單的CSS修復?

 @import url( 'https://necolas.github.io/normalize.css/latest/normalize.css' ); * { outline: 1px solid red; } html, body { overflow: hidden; height: 100%; text-align: center; } h1 { margin: 0; color: #f3f3f3; } .v-cntr { position: relative; top: 50%; transform: translateY( -50% ); } .hdg-wrap { font-size: 5.5rem; position: absolute; top: 48%; right: 0; bottom: 0; left: 0; transform: translateY( -100% ); z-index: -1; } 
 <header class="v-cntr"> <!-- << v-cntr = vertically center --> <!-- ----------------------- HEADING WRAPPER ------------------------ --> <div class="hdg-wrap"> <h1>RIDE</h1> </div> <!-- ------------------------ IMAGE WRAPPER ------------------------- --> <div class="img-wrap"> <img src="http://svgshare.com/i/xL.svg" alt="Logo"> </div> </header> 

我試圖不改變HTML的結構


編輯:我得到的答案是試圖使圖像居中而不是背后的文字。 我可以看到混亂,因為兩個偏離中心。 我將重申:我主要擔心的是在收縮時將h1 ('ride'文本)元素保持在窗口中心。

您可以重置.img-wrap的文本對齊,並使用此CSS將圖像置於其中。

.img-wrap {
  text-align: initial;
  position: relative;
}
.img-wrap img {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

評論后的補充:您可以將相同的原則應用於h1 由於它的父母已經絕對定位,我沒有改變它,只是添加了

h1 {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

這是完整的片段:

 @import url('https://necolas.github.io/normalize.css/latest/normalize.css'); * { outline: 1px solid red; } html, body { overflow: hidden; height: 100%; text-align: center; } h1 { margin: 0; padding: 0; color: #eee; position: absolute; left: 50%; transform: translateX(-50%); } .v-cntr { position: relative; top: 50%; transform: translateY( -50%); } .hdg-wrap { color: #fff; opacity: 0.5; font-size: 5.5rem; position: absolute; top: 48%; right: 0; bottom: 0; left: 0; transform: translateY( -100%); z-index: -1; } .img-wrap { text-align: initial; position: relative; } .img-wrap img { position: absolute; left: 50%; transform: translateX(-50%); } 
 <header class="v-cntr"> <!-- << v-cntr = vertically center --> <!-- -- - - - - - - - - - - - - - HEADING - - - - - - - - - - - - - - --> <div class="hdg-wrap"> <!-- << hdg-wrap = heading wrapper --> <h1>RIDE</h1> </div> <!-- -- - - - - - - - - - - - IMAGE WRAPPER - - - - - - - - - - - - - --> <div class="img-wrap"> <img src="http://svgshare.com/i/xL.svg" alt="Logo"> </div> </header> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM