Search code examples
htmlcssflexboxcenter

How to center an image within a flex item (cell)


I have a 3x3 flexbox with an icon and title in each item/cell. I am just trying to horizontally center the icon (svg image). I tried justify-content: center; but it doesn't seem to work. Can any tell me how to horizontally center an image within a flexbox item (or cell, as I am referring to it as)? Code below.

HTML:

<div class="grid">
    <div class="cell">
        <img src="images/cs_icon_01.svg">
        <div class="service-title">Materials Handling, Warehousing &amp; Storage Facility Management</div>
    </div>
    <div class="cell">Content</div>
    <div class="cell">Content</div>
    <div class="cell">Content</div>
    <div class="cell">Content</div>
    <div class="cell">Content</div>
    <div class="cell">Content</div>
    <div class="cell">Content</div>
    <div class="cell">Content</div>
</div>

CSS:

.grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin-bottom: 130px;
}

.cell {
  flex: 0 0 30%;
  height: 220px;
  margin-bottom: 20px;
  justify-content: center;
}

.grid img {
  width: 45px;
}

.service-title {
  display: inline-block;
  font-family: Montserrat, Helvetica, Arial, sans-serif;
  font-size: 16px;
  font-weight: 300;
  color: #4e4e4e;
  line-height: 24px;
  padding: 20px 16px 4px 16px;
  text-align: center;
}

Solution

  • you can give a try to the classic display+margin:

    .grid img {
      width: 45px;
      display:block;
      margin:auto;/* horizontal center effect */
    }
    

    or use text-align:

    .cell {
      flex: 0 0 30%;
      height: 220px;
      margin-bottom: 20px;
      /*justify-content*/ text-align: center;
    }