提问者:小点点

如何在 div 元素内水平居中图像?


如何在其容器div内居中对齐(水平)图像?

这是HTML和CSS。我还包含了缩略图其他元素的 CSS。它按降序运行,因此最高的元素是一切的容器,最低的元素是一切的内部。

#thumbnailwrapper {
      color: #2A2A2A;
      margin-right: 5px;
      border-radius: 0.2em;
      margin-bottom: 5px;
      background-color: #E9F7FE;
      padding: 5px;
      border: thin solid #DADADA;
      font-size: 15px
}
    
#artiststhumbnail {
      width: 120px;
      height: 108px;
      overflow: hidden;
      border: thin solid #DADADA;
      background-color: white;
}
    
#artiststhumbnail:hover {
      left: 50px
}
<!--link here-->

<a href="NotByDesign">
  <div id="thumbnailwrapper">

    <a href="NotByDesign">

      <!--name here-->
      <b>Not By Design</b>
      <br>

      <div id="artiststhumbnail">

        <a href="NotByDesign">

          <!--image here-->
          <img src="../files/noprofile.jpg" height="100%" alt="Not By Design" border="1" />
        </a>
      </div>

      <div id="genre">Punk</div>

  </div>

好的,我添加了没有PHP的标记,所以应该更容易看到。这两种解决方案在实践中似乎都不起作用。顶部和底部的文本不能居中,图像应该在其容器分区内居中。容器已隐藏溢出,因此我希望看到图像的中心,因为这通常是焦点所在的位置。


共3个答案

匿名用户

#artiststhumbnail a img {
    display:block;
    margin:auto;
}

以下是我的解决方案:http://jsfiddle.net/marvo/3k3CC/2/

匿名用户

CSS flexbox可以在图像父元素上使用justify content:center来实现。要保持图像的纵横比,请添加alignself:flexstart

超文本标记语言

<div class="image-container">
  <img src="http://placehold.it/100x100" />
</div>

CSS

.image-container {
  display: flex;
  justify-content: center;
}

输出:

body {
  background: lightgray;
}
.image-container {
  width: 200px;
  display: flex;
  justify-content: center;
  margin: 10px;
  padding: 10px;
  /* Material design properties */
  background: #fff;
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14), 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 1px 5px 0 rgba(0, 0, 0, 0.12);
}
.image-2 {
  width: 500px;
  align-self: flex-start;  /* to preserve image aspect ratio */
}
.image-3 {
  width: 300px;
  align-self: flex-start;  /* to preserve image aspect ratio */
}
<div class="image-container">
  <img src="http://placehold.it/100x100" />
</div>

<div class="image-container image-2">
  <img src="http://placehold.it/100x100/333" />
</div>

<div class="image-container image-3">
  <img src="http://placehold.it/100x100/666" />
</div>

匿名用户

我刚刚在W3 CSS页面上找到了这个解决方案,它回答了我的问题。

img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

来源:http://www.w3.org/Style/Examples/007/center.en.html