【问题标题】:I can't center the image inside the div我无法在 div 内居中图像
【发布时间】:2015-06-04 08:53:51
【问题描述】:

我尝试将图像居中,但不确定我做错了什么。我应该更改/添加什么以使图像居中?

#img-wrap {
  width:450px;
  clear:both;
  display:block
}
#img-wrap img {
  margin:0 auto;
  text-center:center;
  height:100px;
  width:100px;
  background:#000;
}
<div id='img-wrap'>
  <img src='https://www.google.co.in/images/srpr/logo11w.png' />
</div>

谢谢。

【问题讨论】:

标签: html css


【解决方案1】:

必要的属性被命名为text-align,而不是text-center。此外,您不会将其分配给图像,而是分配给其父容器。

#img-wrap { text-align: center; }

【讨论】:

  • @katan SO 还没有让我。
【解决方案2】:

两个选项,但你似乎混合了它们。

要么将text-align: center 设置为,要么将margin: 0 auto 设置为子元素- 并将该元素设置为block。这是因为img 的默认显示属性为inline-block

文本对齐的父级 - http://jsfiddle.net/BramVanroy/w0jecf01/2/

#img-wrap {
    width:450px;
    border: 3px solid black;
    text-align: center;
}
#img-wrap img {
    height:100px;
    width:100px;
    background:#000;
}

要阻止的孩​​子 - http://jsfiddle.net/BramVanroy/w0jecf01/1/

#img-wrap {
    width:450px;
    border: 3px solid black;
}
#img-wrap img {
    margin:0 auto;
    height:100px;
    width:100px;
    display: block;
    background:#000;
}

【讨论】:

    【解决方案3】:

    在您的 css 中使用以下更改

     #img-wrap {
        width:450px;
        clear:both;
        display:block;
        text-align:center;
    }
    #img-wrap img {
        height:100px;
        width:100px;
        background:#000;
    }
    

    #img-wrap {
       width:450px;
       clear:both;
        display:block;
        text-align:center;
    }
    #img-wrap img {
        margin:0 auto;
        height:100px;
        width:100px;
        background:#000;
        display:block;
    }
    

    【讨论】:

    • 还应该从图片中删除无效的属性名称text-center
    • @SamHolmes 好的,我知道让我做些改变
    • margin:0 auto; 不会有任何影响,除非 img 设置为 display: block,并且没有必要,因为您在父级上有 text-align: center
    • 您也可以将margin-auto; display:block添加到中心显示
    • @Andy 还有更多方法可以在中心显示图像。
    猜你喜欢
    • 1970-01-01
    • 2012-03-03
    • 2012-06-14
    • 1970-01-01
    • 2014-07-12
    • 2013-12-17
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多