因此,我有几个具有动态高度的部分(基于视口),我需要能够将IMG定位为各节之间的分隔线。我能想到的唯一方法是绝对放置图像。问题是我并不总是知道每个部分的固定高度是多少。
因此,是否有一种方法可以添加与位置相对于自身的定位的部分,而无需将空的空间从位置留下:
.section {
width: 100%;
height: 200px;
}
.divider1 {
position: absolute;
left: calc(50vw - 100px);
top: 150px;
}
.divider2 {
position: absolute;
left: calc(50vw - 100px);
top: 350px;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="section blue"></div>
<div class="divider1">
<img width="200" height="100" src="http://www.clipartbest.com/cliparts/ace/o9d/aceo9daEi.jpeg" />
</div>
<div class="section red"></div>
<div class="divider2">
<img width="200" height="100" src="http://www.clipartbest.com/cliparts/ace/o9d/aceo9daEi.jpeg" />
</div>
<div class="section green"></div>
</body>
</html>
将分隔线设置为pseudo-element(我已经使用了 ::after
)。将伪元素与部分元素的底部相关。这样,本节的高度就可以改变,分隔线将在正确的位置。
注意 - 您必须将DIV包装在容器中,因此我们可以在最后一节中禁用::after
。
.section {
position: relative;
width: 100%;
height: 200px;
}
.section:not(:last-child)::after {
position: absolute;
width: 200px;
height: 100px;
bottom: -50px;
left: calc(50% - 100px);
background: url(http://www.clipartbest.com/cliparts/ace/o9d/aceo9daEi.jpeg) no-repeat;
background-size: contain;
content: "";
z-index: 1;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
<div>
<div class="section blue"></div>
<div class="section red"></div>
<div class="section green"></div>
</div>
如果您的图像具有稳定的尺寸:width =" 200px" height =" 100px",那么您可以将它们绝对放置在彩色divs中,并且独立于父级高度:
.section {
width: 100%;
height: 50vh;
position: relative;
}
.section img {
width: 200px;
height: 100px;
display: block;
position: absolute;
margin-left: calc(50% - 100px);
margin-top: -50px;
}
.blue {
background-color: blue;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
<div class="section blue"></div>
<div class="section red">
<img src="http://www.clipartbest.com/cliparts/ace/o9d/aceo9daEi.jpeg" />
</div>
<div class="section green">
<img src="http://www.clipartbest.com/cliparts/ace/o9d/aceo9daEi.jpeg" />
</div>