0

In the following code, I'm trying to vertical/horizontal center the image inside the red block. Note that after the block there is a centered text.

I guess it is simple, but I've tried many solutions (1, 2, 3, 4, 5), it still does not work as expected...

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>

Constraints:

I display several blocks, and the width:33% and float: left comes from Bootstrap classes and can not be deleted.

Community
  • 1
  • 1

1 Answers1

3

Just use below CSS Code for this

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

for Updated Fiddle 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>
Super User
  • 9,448
  • 3
  • 31
  • 47
  • http://jsfiddle.net/3mkfza5u/ As you can see, it makes the legend failed. –  Jan 23 '17 at 11:08