我试图垂直居中一个具有绝对位置的内联元素,它位于一个大小为百分比的div内,我想在没有flexbox的情况下这样做。它必须适用于各种宽高比。
.outerElement1 {
height: 200px;
width: 250px;
background: gray;
font-size: 0;
line-height: 0;
}
.outerElement2 {
height: 250px;
width: 200px;
background: gray;
font-size: 0;
line-height: 0;
}
.innerElement {
height: 100%;
width: 100%;
background: tomato;
opacity: 0.5;
position: relative;
}
h2 {
font-size: 20px;
height: 100%;
width: 100%;
border: 4px solid white;
display: block;
position: absolute;
box-sizing: border-box;
margin: 0;
padding-top: 50%;
}

<div class="outerElement1">
<div class="innerElement">
<h2>Text</h2>
</div>
</div>
<div class="outerElement2">
<div class="innerElement">
<h2>Text</h2>
</div>
</div>
&#13;
如果有人知道如何实现这一目标,我将非常感激!
答案 0 :(得分:0)
由于您正在修复outerElement的高度,因此您还可以将line-height
修改为等于高度,然后在h2标记上使用line-height: inherit;
,使其始终居中。
.outerElement1 {
height: 200px;
width: 250px;
background: gray;
font-size: 0;
line-height: 200px;
}
.outerElement2 {
height: 250px;
width: 200px;
background: gray;
font-size: 0;
line-height: 250px;
}
.outerElement3 {
height: 20vh;
width: 200px;
background: gray;
font-size: 0;
line-height: 20vh;
}
.innerElement {
height: 100%;
width: 100%;
background: tomato;
opacity: 0.5;
position: relative;
}
h2 {
font-size: 20px;
top: 0;
right: 0;
left: 0;
bottom: 0;
border: 4px solid white;
position: absolute;
box-sizing: border-box;
margin: 0;
line-height: inherit;
text-align: center;
}
<div class="outerElement1">
<div class="innerElement">
<h2>Text</h2>
</div>
</div>
<div class="outerElement2">
<div class="innerElement">
<h2>Text</h2>
</div>
</div>
<div class="outerElement3">
<div class="innerElement">
<h2>Text</h2>
</div>
</div>