【问题标题】:How to center an image within a flex item (cell)如何在弹性项目(单元格)中居中图像
【发布时间】:2017-06-20 22:23:41
【问题描述】:

我有一个 3x3 弹性框,每个项目/单元格中都有一个图标和标题。我只是想将图标水平居中(svg 图像)。我试过justify-content: center;,但它似乎不起作用。任何人都可以告诉我如何在 flexbox 项目(或单元格,正如我所指的那样)中水平居中图像吗?代码如下。

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

【问题讨论】:

  • 我们称它们为“元素”,而不是“项目”,或者更糟糕的是,让人想起表格的“单元格”。 Flex 元素及其内容是标准的 HTML 元素。
  • 谢谢罗伯。我在一篇 flexbox 文章中读到它是容器 > 项目。可能只是那个作者的措辞。我只是在使用单元格来明确以什么为中心。

标签: html css flexbox center


【解决方案1】:

你可以试试经典的display+margin

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

或使用文本对齐:

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

【讨论】:

  • 什么……!我确定我已经尝试过了。我猜不是——它奏效了!谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 2018-03-23
  • 2020-02-06
  • 1970-01-01
  • 2017-11-28
相关资源
最近更新 更多