我正在尝试将具有绝对位置的内联元素垂直居中,该元素位于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>
如果有人对如何实现有一个想法,我将非常感激!
最佳答案
由于您要固定externalElement的高度,因此还可以将line-height
固定为等于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>
关于html - 在具有百分比且不包含flexbox的div内使具有绝对位置的内联元素垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47371471/