【问题标题】:How to center the image inside of figure?如何使图像在图中居中?
【发布时间】:2015-04-04 04:34:36
【问题描述】:

我已尽一切努力将图像在页面上居中,仅用于 @media 屏幕和 (max-width:480px),但是没有任何效果。

代码如下:

前端

<figure class="img1 embed">

<img src="Images/testimonial-2.jpg" alt=""/>

</figure>

CSS

/*** Base Caption Styles ***/
figure.embed,
figure.embed-top,
figure.overlay,
figure.embed-over {
    display: inline-block;
    vertical-align: top;
    position: relative;
    margin: 0.5em;
    font-size: 0.8em;
    background: white;
    overflow: hidden;
    float: right;
}
figure.embed img,
figure.embed-top img,
figure.overlay img,
figure.embed-over img {
    width: 100%;
    display: block;
}
figure.embed figcaption,
figure.embed-top figcaption,
figure.overlay figcaption,
figure.embed-over figcaption {
    width: 100%;
    padding: 0.5em;
    /* neutral theme */
    color: rgba(50,50,50,1.0);
    background: rgba(200,200,200,0.825);
}

谁能告诉我需要对这个代码做什么才能使图像居中?我试过 display: block;边距:0 自动和边距左:自动; margin-right: auto,但无济于事。

任何帮助将不胜感激!

【问题讨论】:

  • 你在第一组规则中得到了浮动 + 你的 img 是宽度为 100% 的显示块
  • 我知道,但是,我的问题是如何编辑上面的代码以使用媒体查询 480px 居中图像?
  • 您是否在媒体查询或图像居中遇到问题?关于居中图像有很多问题。 jsfiddle.net/64d71yjg

标签: css image center centering


【解决方案1】:

包含您的图像的元素(figure)当前是向右浮动的。相反,将它放在一个容器中,该容器本身就是一个块元素。使 figure 成为内联块元素。您可以通过在外部容器上设置text-align: center 将图形在其容器中居中(确保将其设置回initial,因此其中的文本也不会居中)。此外,您可以通过删除 width:100% 并添加 auto margin-leftmargin-right 来使图像居中。

.outer {
  display: block;
  text-align: center;
}

/*** Base Caption Styles ***/
figure.embed,
figure.embed-top,
figure.overlay,
figure.embed-over {
    display: inline-block;
    text-align: initial;
    vertical-align: top;
    position: relative;
    margin: 0.5em;
    font-size: 0.8em;
    background: white;
    overflow: hidden;
}
figure.embed img,
figure.embed-top img,
figure.overlay img,
figure.embed-over img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}
figure.embed figcaption,
figure.embed-top figcaption,
figure.overlay figcaption,
figure.embed-over figcaption {
    width: 100%;
    padding: 0.5em;
    /* neutral theme */
    color: rgba(50,50,50,1.0);
    background: rgba(200,200,200,0.825);
}

figcaption {
    display: block;
}
<div class="outer">
<figure class="img1 embed news">
  <img src="http://placehold.it/250" alt="">
  <figcaption> Text. </figcaption>
</figure>
</div>

【讨论】:

  • 你也可以让figure显示块并移除宽度100%
  • 这行得通(谢谢!),但是,现在 figcaption 不再包含在图像中(在其他页面上)。它横跨页面的宽度。关于如何修改 css 使其包含在图像中的任何想法?前端:
    placehold.it/250" alt="">
    文字。
  • 查理,我必须更新我的示例以将这个附加元素考虑在内 - 在这个示例中,有一个新的包含 div - 希望这对您的目的来说没问题。
  • @MatthewG 谢谢。我现在遇到的问题是将浏览器缩小到 360px 时,图像不完全集中在下面的

    上:'

    文字。
    '

    文字。

  • 我很高兴您发现我的回答很有帮助,如果您的问题中未包含更多详细信息,您可能需要填写更多详细信息或提出其他问题。但很高兴它到目前为止还有效!
猜你喜欢
  • 2014-02-28
  • 2016-04-23
  • 2012-05-06
  • 1970-01-01
  • 2021-03-25
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多