如何在这种特定情况下将div中的文本居中?

时间:2015-02-10 20:11:58

标签: css image responsive-design centering

如何将文本置于该框内?

以下是我希望元素排序的方式:

enter image description here

在较小的屏幕中,元素堆叠在一起,而.text-box div包含我想要居中的文本,具有固定的高度。对于较大的宽度,.text-box div应该具有较高图像的高度和高度减去较短图像的高度

See the Fiddle here

HTML

  <div id="wrapper">
    <div class="box">
      <img class="img-large" src="http://placekitten.com/900/800" alt=""/>
    </div>
    <div class="box">
        <img src="http://placekitten.com/900/400" alt=""/>    
    </div>
    <div class="box-text">
        <div class="vcenter-outer">
            <div class="vcenter-inner">
                <p>center this text vertically</p>  
            </div>
        </div>
    </div>
  </div>

CSS

#wrapper {
    background: #ffeaea;
    height: 100vh;
}
img {
    width: 100%;
    display: block;
}
.img-large {
    height: 100vh;
    width: auto;
}
.box {
    position: relative;
    width: 100%;
    overflow: hidden;
}
.box-text {
    text-align: center;
    background: yellow;
    height: 100%;
}

@media only screen and (min-width: 768px) {
    .box {
        float: left;
        width: 50%;
    }
}

.vcenter-outer {
    background: yellow;
    display: table;
}

.vcenter-inner {
    background: lightblue;
    display: table-cell;
    vertical-align: middle;
}

为什么.text-box div跨越整个包装器?

1 个答案:

答案 0 :(得分:1)

基本上你可以使用display:flex和float一起

&#13;
&#13;
.trio {
  height:100vh;
  width:100vh;
}
.trio>div {
  float:left;
  display:flex;
  align-items:center;
  justify-content:center;
  width:50vh;
  height:50vh;
  box-shadow:inset 0 0 0 2px;
}
.trio .first {
  height:100vh;
}
&#13;
<div class="trio">
  <div class="first">
    <p>Center</p>
  </div>
  <div class="next">
    <p>Center</p>
  </div>
  <div class="next">
    <p>Center</p>
  </div>
</div>
&#13;
&#13;
&#13;

display:table也可以使用额外的div级别,同样的想法:float + vh

codepen to play with