如何垂直对齐div?

时间:2017-09-09 17:21:40

标签: html css html5 css3

https://codepen.io/anon/pen/LjwyvR

我想在中间垂直对齐棕褐色容器/文本容器。像这样。

https://imgur.com/a/TRX6c

我不想使用transform:translate方法,因为我想支持IE8

<div class="container clearfix">
  <div class="text-container">
    <h3>Title</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod mauris non tellus luctus, ac dignissim arcu tincidunt. Praesent vulputate orci nibh, a egestas mauris interdum vitae. Sed convallis porta dui efficitur interdum. Sed id porta arcu, vitae ultrn porttitor nisi ac placerat vestibulum.</p>
  </div>
  <div class="img"></div>
</div>



.container {
  width: 100%;
  background-color: grey;
}

.text-container, .img {
  width: 50%;
  float: left;
}

.text-container {  
  background-color: tan;  
}

.img {
  height: 300px;  
  background: url('https://static.pexels.com/photos/56875/tree-dawn-nature-bucovina-56875.jpeg');  
  background-size: cover;  
}


.clearfix:after {
   content: " ";
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

1 个答案:

答案 0 :(得分:1)

您必须在父容器上使用display: table

HTML:

<div class="container clearfix">
  <div class="text">
    <div class="text-container">
      <h3>Title</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod mauris non tellus luctus, ac dignissim arcu tincidunt. Praesent vulputate orci nibh, a egestas mauris interdum vitae. Sed convallis porta dui efficitur interdum. Sed id porta arcu, vitae ultrn porttitor nisi ac placerat vestibulum.</p>
    </div>
  </div>
  <div class="img"></div>
</div>

和CSS:

.container {
  width: 100%;
  background-color: grey;
  display: table;
}

.text, .img {
  display: table-cell;
  width: 50%;
  vertical-align: middle;
}

.text-container {  
  background-color: tan;  

}

.img {
  height: 300px;  
  background: url('https://static.pexels.com/photos/56875/tree-dawn-nature-bucovina-56875.jpeg');  
  background-size: cover;  
}
.clearfix:after {
   content: " ";
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Codepen:https://codepen.io/anon/pen/LjwyvR