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

心已入冬 提交于 2019-12-25 09:08:15

问题


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;
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/42026081/how-to-center-an-image-within-a-flex-item-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!