在下面的代码中,我试图将图像垂直/水平居中在红色块内。请注意,在块之后有一个居中的文本。
我想这很简单,但我尝试了很多解决方案(1,2,3,4,5),它仍然没有按预期工作......
.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类,可以不删除。
答案 0 :(得分:3)
只需使用下面的CSS代码
.child {
background-color: red;
height: 150px;
width: 150px;
display: flex;
align-items: center;
justify-content: center;
}
更新小提琴click here
.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;