<!DOCTYPE html>
<html>
<head>
<style>
.Background {
background-image:url("https://images.unsplash.com/photo-1517524285303-d6fc683dddf8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1275&q=80");
height: 220px;
background-size: 100% 100%;
background-repeat: no-repeat;
}
.Relative {
position:relative;
}
.Absolute {
position: absolute;
left: 100px;
top: 150px;
border: 1px solid red;
}
h2 {
}
</style>
</head>
<body>
<div class="Main">
<div class="Relative">
<div class="Background"></div>
<div class="Absolute">
<h1>Hi</h1>
<h1>Hi</h1>
<h1>Hi</h1>
<h1>Hi</h1>
</div>
</div>
<footer>With absolute positioning, an element can be placed anywhere on a page. The heading below is placed 100px from the left of the page and 150px from the top of the page.</footer>
</div>
绝对位置的元素显示在页脚上。我想要的是具有类相对的元素,以占用具有类绝对的孩子的高度。
现在在这里,我将"背景"成为相对div的"背景",并将您的"绝对"div与相对相对,以便它给出您内容div的父元素的高度。在这种情况下,背景将始终采用父元素的高度和宽度,无论您可以输入多少文本,它永远不会重叠页脚。希望它有帮助
.Background {
background-image:url("https://images.unsplash.com/photo-1517524285303-d6fc683dddf8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1275&q=80");
height: 220px;
background-size: 100% 100%;
background-repeat: no-repeat;
position: absolute;
height: 100%;
width: 100%;
z-index:0;
}
.Relative {
position:relative;
}
.Absolute {
position:relative;
z-index: 1;
}
h2 {
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="Main">
<div class="Relative">
<div class="Background"></div>
<div class="Absolute">
<h1>Hi</h1>
<h1>Hi</h1>
<h1>Hi</h1>
<h1>Hi</h1>
<h1>Hi</h1>
</div>
</div>
<footer>With absolute positioning, an element can be placed anywhere on a page. The heading below is placed 100px from the left of the page and 150px from the top of the page.</footer>
</div>
function setHeight() {
let rel = document.querySelector(".Relative");
let abs = document.querySelector(".Absolute");
let hei = abs.scrollHeight;
hei += abs.offsetTop;
rel.style.height = hei + "px";
}
setHeight();
window.addEventListener("resize", setHeight);
.Background {
background-image:url("https://images.unsplash.com/photo-1517524285303-d6fc683dddf8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1275&q=80");
height: 220px;
background-size: 100% 100%;
background-repeat: no-repeat;
}
.Relative {
position:relative;
background-color: #333;
}
.Absolute {
position: absolute;
left: 100px;
top: 150px;
border: 1px solid red;
}
<div class="Main">
<div class="Relative">
<div class="Background"></div>
<div class="Absolute">
<h1>Hi</h1>
<h1>Hi</h1>
<h1>Hi</h1>
<h1>Hi</h1>
</div>
</div>
<footer>With absolute positioning, an element can be placed anywhere on a page. The heading below is placed 100px from the left of the page and 150px from the top of the page.</footer>
</div>