簡體   English   中英

CSS:最小高度為100%的div中居中文本溢出其邊界

[英]CSS: centered text in div with min-height:100% overflows its borders

我有一個包含部分的頁面,第一部分的最小高度為100%(html和body也設置為100%),以便第一部分始終在頁面加載時填充整個視口。 到目前為止,我已經完成了此操作。

對我來說,問題是我想在垂直和水平居中的第一部分中放置文本。 這也可以,但這是問題所在:

我降低了瀏覽器的高度->文本部分超出了視口。 沒關系。 但是,當我向下滾動時,第二部分已經開始,但是文本使第二部分溢出,並且第一部分沒有根據所屬文本擴展其高度。

對不起,我的英語不好,希望您能理解我的意思。

我認為min-height意味着第一節的高度根據文本的數量而變化,但是每次它只有100%的視口高度時,不適合該空間的部分就會與該節重疊。

那里可能出什么事了?

  #section-0-bg-image-red { width:100%; min-height:100%; position:relative; -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */ -moz-box-sizing: border-box; /* Firefox, other Gecko */ box-sizing: border-box; /* background: some full page image with no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='...', sizingMethod='scale'); -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='...', sizingMethod='scale')"; */ background-color:red; } #section-0-white-overlay { background: rgba(255,255,255,0.8); width:100%; height:100%; position:absolute; } .outer { display: table; position: absolute; height: 100%; width: 100%; } .middle { display: table-cell; vertical-align: middle; } .inner { margin-left: auto; margin-right: auto; max-width: 200px; padding-left: 20px; padding-right: 20px; } .headline { font-size:24px; text-align:center; } #section-1-yellow { background-color:yellow; width:100%; height:600px; } 
  <div id="section-0-bg-image-red"> <div id="section-0-white-overlay"> <div class="outer"> <div class="middle"> <div class="inner"> <div class="headline">text to be centered horizontally and vertically but overlaps the first section when window height is decreased and user scrolls down </div> </div> </div> </div> </div> </div> <div id="section-1-yellow"></div> 

使用jQuery解決方案進行更新

嘿,

在花了更多時間后,我發現是什么使第一節無法適應文本:

為了使文本垂直居中,必須將“外部”類的div絕對定位,但是這種方式100%高度的部分“沒有理由”適應任何內容。 猜猜這是CSS基礎知識之一,但是我知道什么呢? 太少了 ;)

因此,我放棄了CSS居中解決方案,並決定通過jQuery根據窗口高度設置文本div的padding-top來實現某種文本的垂直居中:

$(window).on('load resize', function(){

var paddingHeight = ( $(window).height() / 3 ) - 80;


 $(".inner").css({"padding-top": paddingHeight + "px"});    

});

可能不是很優雅,但是可以達到預期的效果。

我想我明白你在說什么。 我認為您應該嘗試將高度設置為完整視口,而不是使用min-height

height:100vh;

這將使具有該標簽的任何元素填充整個視口,而不管視口大小如何。

這是JSfiddle的鏈接。 讓我知道您是否打算這樣做。

https://jsfiddle.net/w4k6rzsy/1/

暫無
暫無

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

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