为什么保证金:0自动无法在div中居中图像?

时间:2017-06-27 02:11:41

标签: html css

图像元素可以与margin:0px 50px 0px 50px;水平居中。



.wrapper {
  width: 175px;
  height: 100px;
  border: 1px solid red;
}

img {
  margin: 0px 50px 0px 50px;
}

<div class="wrapper">
  <img src="http://i.imgur.com/9OIT14w.jpg" alt="">
</div>
&#13;
&#13;
&#13;

在这种情况下,margin:0 auto; == margin:0px 50px 0px 50px; 因此,将margin:0px 50px 0px 50px;写为margin:0 auto;等于 为什么它不能以margin:0 auto;为中心?

&#13;
&#13;
.wrapper {
  width: 175px;
  height: 100px;
  border: 1px solid red;
}

img {
  margin: 0 auto;
}
&#13;
<div class="wrapper">
  <img src="http://i.imgur.com/9OIT14w.jpg" alt="">
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

你错过了display:block

.wrapper {
  width: 175px;
  height: 100px;
  border: 1px solid red;
}

.img1 {
  margin: 0 auto;
  display: block
}
<div class="wrapper">
  <img class="img1" src="http://i.imgur.com/9OIT14w.jpg" alt="">
</div>

答案 1 :(得分:0)

我确信有更好/更有效的方法。但...

这是我用于在div内垂直和水平居中图像,而维护 div的固定尺寸。图片永远不会裁剪 / 拉伸

body {
  text-align: center;
  margin: 0 auto;
}

.my-image-parent {
  margin:1em auto;
  width: 350px;
  max-width:100%;
  height: 200px;
  line-height: 200px; /* should match your div height */
  text-align: center;
  font-size: 0;
  background: #131418;
}


/*fluff */
.bg1 {background: url(https://unsplash.it/799/799);}
.bg2 {background: url(https://unsplash.it/800/400);}
.bg3 {background: url(https://unsplash.it/400/800);}
/* end fluff */


.my-image {
  width: auto;
  height: 100%;
  vertical-align: middle;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
}
<h4>Works for square, landsacape and portrait images.</h4>

<div class="my-image-parent">
  <div class="my-image bg1"></div>
</div>
<br>
<div class="my-image-parent">
  <div class="my-image bg2"></div>
</div>
<br>
<div class="my-image-parent">
  <div class="my-image bg3"></div>
</div>

答案 2 :(得分:0)

由于img标记是inline-block元素,margin: 0 auto;将不起作用。其显示属性必须设置为display: block;

.wrapper {
  width: 175px;
  height: 100px;
  border: 1px solid red;
}

img {
  margin: 0 auto;
  display: block;
}
<div class="wrapper">
  <img src="http://i.imgur.com/9OIT14w.jpg" alt="">
</div>

您还可以为外包装添加text-align: center;以使图像居中。

.wrapper {
  width: 175px;
  height: 100px;
  border: 1px solid red;
  text-align: center;
}
<div class="wrapper">
  <img src="http://i.imgur.com/9OIT14w.jpg" alt="">
</div>

编辑:

内联块和内联块元素没有width属性,因此无法计算“auto”。

参考:Why centering with margin 0 auto works with display:block but does not work with display:inline-block ?