html - 在具有百分比且不包含flexbox的div内使具有绝对位置的内联元素垂直居中

标签 html css

我正在尝试将具有绝对位置的内联元素垂直居中,该元素位于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/

相关文章:

html - 为什么这不会在顶部、右侧和底部有边框线,而是在左侧?

javascript - 单击其他按钮时如何使div自动隐藏

jquery - 如何从 SVG 波浪中隐藏圆圈?

html - 将 rvest::html_nodes() 与来自 SelectorGadget 或 Chrome 开发者工具的 CSS 标签一起使用总是返回空列表

javascript - 检查数据属性值是否等于字符串

JQuery - 显示错误和正确的图标进行验证

javascript - 如何在不重新编码的情况下扩大我的网站

php - TTF 字体不显示在动态 SVG 中

html - 线性渐变在 :before pseudo 中不起作用

jquery - 无法在 jquery 中删除克隆