在下面的代码中,我试图将图像垂直/水平居中在红色块内。请注意,在块之后有一个居中的文本。
我想这很简单,但是我尝试了许多解决方案(1,2,3,4,5),但仍无法按预期工作...
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类,不能删除。 最佳答案
只需使用下面的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;
}
<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>