div内垂直/水平居中的具体问题

时间:2017-01-23 11:03:46

标签: html css image

在下面的代码中,我试图将图像垂直/水平居中在红色块内。请注意,在块之后有一个居中的文本。

我想这很简单,但我尝试了很多解决方案(12345),它仍然没有按预期工作......

JSFiddle

.parent {
  text-align: center;
  width: 33%;
  float: left;
}

.child {
  background-color: red;
  height: 150px;
  width: 150px;
  display: inline-block;
  vertical-align: middle;
}
<div class="parent">
  <div class="child">
    <img src="http://dlg.galileo.usg.edu/images/Historic_Architecture_and_Landscapes.gif" />
  </div>
  <p>Legend of the block</p>
</div>

<div class="parent">
  <div class="child">
    <img src="http://dlg.galileo.usg.edu/images/Historic_Architecture_and_Landscapes.gif" />
  </div>
  <p>Legend of the block</p>
</div>

<div class="parent">
  <div class="child">
    <img src="http://dlg.galileo.usg.edu/images/Historic_Architecture_and_Landscapes.gif" />
  </div>
  <p>Legend of the block</p>
</div>

约束:

我显示了几个块,width:33%float: left来自Bootstrap类,可以删除。

1 个答案:

答案 0 :(得分:3)

只需使用下面的CSS代码

.child {
    background-color: red;
    height: 150px;
    width: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
}

更新小提琴click here

&#13;
&#13;
.parent {
  text-align: center;
  width: calc(100% /3);
  float: left;
}
.child {
  background-color: red;
  height: 150px;
  width: 150px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}
&#13;
<div class="parent">
  <div class="child">
    <img src="http://dlg.galileo.usg.edu/images/Historic_Architecture_and_Landscapes.gif" />
  </div>
  <p>Legend of the block</p>
</div>

<div class="parent">
  <div class="child">
    <img src="http://dlg.galileo.usg.edu/images/Historic_Architecture_and_Landscapes.gif" />
  </div>
  <p>Legend of the block</p>
</div>

<div class="parent">
  <div class="child">
    <img src="http://dlg.galileo.usg.edu/images/Historic_Architecture_and_Landscapes.gif" />
  </div>
  <p>Legend of the block</p>
</div>
&#13;
&#13;
&#13;

相关问题