我會盡量用最簡單的方式解釋這一點。我想要一個“祖父”元素,它需要 100vh 的高度和 100% 的視口寬度,就像一個部分,里面會有一個父元素,其中包含一個具有絕對定位的子元素。
<body>
<div class="container">
<div class="parentElement">
<div class="ChildrenElement">
</div>
</div>
</div>
</body>
造型:
<style>
.container {
background-color:black;
min-height:100vh;
display:flex;
justify-content:center;
align-items:center;
}
.parentElement {
position:relative;
background-color:blue;
width: 800px;
height: 200px;
}
.ChildrenElement {
position:absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255,192,203, 0.5);
transform: translate(10%);
}
</style>
輸出:

但我希望這是這樣的:

紅色框代表子元素,如果它遠離父元素,它應該在黑色背景后面。
編碼:
https://jsbin.com/pemasacazi/edit?html
uj5u.com熱心網友回復:
我相信您正在尋找oveflow:hidden(https://developer.mozilla.org/en-US/docs/Web/CSS/overflow)。
.container {
background-color:black;
min-height:100vh;
display:flex;
justify-content:center;
align-items:center;
}
.parentElement {
position:relative;
background-color:blue;
width: 800px;
height: 200px;
max-width: 90%;
margin: auto;
overflow:hidden;
}
.ChildrenElement {
position:absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255,192,203, 0.5);
transform: translate(10%);
}
<!DOCTYPE html>
<body>
<div class="container">
<div class="parentElement">
<div class="ChildrenElement">
</div>
</div>
</div>
</body>
uj5u.com熱心網友回復:
這里的問題是 HTML 總是將父元素放在子元素后面,以便它們可見。我們可以簡單地通過交換父元素和子元素的類來改變它:
.container {
background-color: black;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.parentElement {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 192, 203, 0.5);
transform: translate(10%);
}
.ChildrenElement {
position: relative;
background-color: blue;
width: 800px;
height: 200px;
}
<body>
<div class="container">
<div class="ChildrenElement">
<div class="parentElement">
</div>
</div>
</div>
</body>
現在,即使元素的位置發生了變化,我也看不出任何區別。請評論這是否有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/322081.html
