为什么这个绝对定位的div不垂直居中?

时间:2015-12-16 22:10:16

标签: html css html5 css3

我需要多行文本在父级中垂直居中。我需要孩子为position: absolute;因为它背后会有其他物品。我无法弄清楚如何使孩子(包含文本的div)垂直居中。 (我也尝试用display: table-cell做这件事,但也无法做到这一点)

https://jsfiddle.net/t7q1ffm2/

HTML:

<div class="box">
  <div class="text">This has some text in it that's long</div>
</div>
<div class="box">
  <div class="text">Short text</div>
</div>

CSS:

    .box
    {
      position: relative;
      top: 0em;
      left: 0em;
      width: 125px;
      height: 125px;
      -webkit-flex-grow: 1;
      -moz-flex-grow: 1;
      -ms-flex-grow: 1;
      flex-grow: 1;
      margin-right: .625em;
      margin-bottom: .5em;
      text-decoration: none;
      overflow: hidden;
      display: table;
      background-color: red;
    }

    .box .text
    {
      position: absolute;
      top: 0;
      bottom: 0;
      left:0;
      right:0;
      margin: auto;
      width:100%;
      height: 50%;
      font-family: Arial, Helvetica;
      font-size: 1em;
      font-weight: normal;
      line-height: 1.125em;
      color: #ffffff;
      text-align: center;
      z-index: 2;
    }

3 个答案:

答案 0 :(得分:2)

如果您想使用位置 relative / absolute ,则必须在绝对元素上添加transform: translate(-50%, -50%);以进行居中对齐。

.box{
  position: relative;
  top: 0em;
  left: 0em;
  width: 125px;
  height: 125px;
  margin-right: .625em;
  margin-bottom: .5em;
  text-decoration: none;
  overflow: hidden;
  background-color: red;
}

.box .text {
  position: absolute;
  top: 50%;
  left:50%;
  width: 100%;
  font-family: Arial, Helvetica;
  font-size: 1em;
  font-weight: normal;
  color: #ffffff;
  text-align: center;
  z-index: 2;
  transform: translate(-50%, -50%);
}
<div class="box">
  <div class="text">This has some text in it that's long</div>
</div>
<div class="box">
  <div class="text">Short text</div>
</div>

答案 1 :(得分:1)

CSS属性table-cell确实有效:

HTML:

<div class="box">
    <div class="text">This has some text in it that's long</div>
</div>
<div class="box">
    <div class="text">Short text</div>
</div>

CSS:

.box {
  width: 130px;
  height: 130px;
  display: table;
}

.text {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

但是,你需要把它包装在另一个盒子里。

这个小提琴说明了您的确切用例:https://jsfiddle.net/stgermaniac/qdc84bxo/

答案 2 :(得分:1)

使用flexbox是您最好的选择。 Here is my fiddle,这是我使用的CSS(我剪掉了一些不必要的CSS):

.box {
    position: relative;
    top: 0em;
    left: 0em;
    width: 125px;
    height: 125px;
    display: flex;
    align-items: center;
    margin-right: .625em;
    margin-bottom: .5em;
    text-decoration: none;
    overflow: hidden;
    background-color: red;
}

.box .text {
    margin: auto;
    width:100%;
    font-family: Arial, Helvetica;
    font-size: 1em;
    font-weight: normal;
    line-height: 1.125em;
    color: #ffffff;
    text-align: center;
    z-index: 2;
}
相关问题