我正在尝试将所有 div 垂直对齐,如图所示。到目前为止,我所有的边距和边距都以 % 表示,并且可以正常工作。但我认为这有点老派,也许可以使用另一种方法来完成。
显示表格、表格单元格、flex 等其他解决方案根本无济于事...
.holder {
width:80%;
height:30%;
position: relative;
margin: 0 auto;
}
.item-1 {
position: absolute;
z-index: 1;
width: 20%;
height: 20%;
background: red;
left: 0;
}
.item-2 {
position: absolute;
z-index: 2;
width: 25%;
height: 30%;
background: blue;
right:0;
}
.item-1:after, .item-2:after {
content:'';
display: block;
padding-bottom: 100%;
}
.txt-holder {
position: absolute;
z-index: 11;
width: 40%;
margin: 0 auto;
background: gold;
left: 0;
right: 0;
}
基本上 html 结构是这样的。
<div class="holder">
<div class="item-1"></div>
<div class="txt-holder">
<h1>header title</h1>
<p>any texts</p>
</div>
<div class="item-2"></div>
</div>
最佳答案
您使用那种解决方案是否正确?
(查看代码片段中的一些评论)
/* Added body, because your .holder was 30% height of nothing as no parent had a size */
body {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding-top: 40px; /* Adding this offset for better visibility when the snippet isn't full-size */
}
/* Added these two classes */
.border1 { /* For better visibility of the objects */
border: 1px solid black;
}
.center-y { /* For vertical centering, the parent element needs to be relative */
position: absolute;
top: 50%;
transform: translateY(-50%);
}
/* Modified some below */
.holder {
width: 80%;
height: 30%;
position: relative;
margin: 0 auto;
}
.item-1 {
/*position: absolute;*/
z-index: 1;
width: 20%;
height: 20%;
background: red;
left: 0;
}
.item-2 {
/*position: absolute;*/
z-index: 2;
width: 25%;
height: 30%;
background: blue;
right: 0;
}
/* What the :afters are used for ? */
.item-1:after,
.item-2:after {
content: '';
display: block;
padding-bottom: 100%;
}
.txt-holder {
/* position: absolute; */
z-index: 11;
width: 40%;
margin: 0 auto;
background: gold;
left: 0;
right: 0;
}
<body>
<div class="holder border1">
<div class="item-1 center-y border1"></div>
<div class="txt-holder center-y border1">
<h1>header title</h1>
<p>any texts</p>
</div>
<div class="item-2 center-y border1"></div>
</div>
</body>
希望对您有所帮助。
关于html - 以 % 为单位的 div 高度中的响应式垂直对齐元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41691651/