我有一個絕對元素,即背景。我不能將它設定為 div 的背景,因為它是影片的并且需要 2 個 css 類。我簡化了它以讓您理解問題。
我想將這個絕對元素的高度設定為與其父元素相同的高度,該元素包含所有其他元素,到達頁面底部。所以我用作背景的這個絕對元素應該覆寫所有背景頁面,但繼承不起作用。
我也嘗試過height:100%,但沒有奏效。它僅在我手動設定高度時才有效,但這樣做沒有回應。
.stars {
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
width:inherit;
height:inherit;
display:block;
}
.stars {
background:#000 url(http://www.script-tutorials.com/demos/360/images/stars.png) repeat top center;
z-index:0;
}
.main-content {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
flex-wrap: wrap;
align-content: center;
justify-content: center;
align-items: center;
}
.home-container {
display: flex;
flex-direction: column;
align-content: center;
justify-content: center;
align-items: center;
flex-wrap: nowrap;
width: 100%;
z-index: 5;
}
.genericDiv1, .genericDiv2, .genericDiv3 {
width: 200px;
height: 200px;
}
.genericDiv1 {
background-color:#f00;
}
.genericDiv2 {
background-color:#00ff76;
}
.genericDiv3 {
background-color:#2900ff;
}
<body>
<div class="main-content">
<div class="stars"></div>
<div class="home-container">
<div class="genericDiv1"></div>
<div class="genericDiv2"></div>
<div class="genericDiv3"></div>
</div>
</div>
</body>
我想指定如果我將.main-content類設定為特定的高度,它就可以作業。但正如我之前所說,這種方式是沒有回應的。
uj5u.com熱心網友回復:
要解決此問題,您需要通過相對定位其父 div來正確定位.stars.main-contentdiv 。(絕對定位元素需要它們的父元素相對定位,否則它們將絕對定位到 body 元素)。然后將高度設定.main-content為100vh(不是100%,因為它的父級body沒有指定高度)占據視口(即螢屏)的全高。
將 div 相對定位,
.main-content并將高度定位到 100vh。現在.starsdiv 可以繼承這個完整的高度。像這樣:.main-content { ... position: relative; height: 100vh; ... }或者,將 body 元素的高度設定為
100vhfirst,然后將.main-contentdiv 的高度設定為100%以繼承視口的完整高度。body { height: 100vh; } .main-content { ... position: relative; height: 100%; ... }padding此外,通過將所有元素的andmargin屬性設定為并為所有元素0設定屬性,洗掉瀏覽器默認的填充和邊距,并防止頁面上元素的寬度和高度超出范圍box-sizing: border-box。將它放在 CSS 的頂部(這是一個很好的 CSS 實踐)。* { box-sizing: border-box; padding: 0; margin: 0; }
uj5u.com熱心網友回復:
請在你的 css 中試試這個: ??? -
洗掉height : 100%并
添加.main-contentheight:100vh
-添加position:relative到.main-content
告訴我發生了什么事。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/474061.html
