css - 边距:自动不居中图像

标签 css margin

我想将一组并排排列的图像居中。尽管使用了 margin: auto,图像仍然排在左边。我在另一个线程中读到要添加 display: block 但这也不起作用。想法?

<div style="margin: auto; display:block;">
  <p>
    <img src="/wp-content/uploads/2015/05/tca_horizontal_blue.gif"
         style="float: left;" alt="" width="200px" height="93px" />
    <img src="/wp-content/uploads/2015/05/nea-logo-e1431885075484.png"
         style="float: left;" alt="" width="218px" height="93px" />
    <img src="/wp-content/uploads/2015/05/Arts-Committee-color1-e1431885177830.png"
         style="float: left;" alt="" width="155px" height="93px" />
  </p>
</div>

最佳答案

根据 §10.3.3 , margin: 0 auto 居中 block 级元素因为

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

但是,如果 widthauto,这就没用了,因为这样 block 将填充它的包含 block :

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

相反,您可以使用表格显示。根据§17.5.2 ,

if the margins of a table are set to '0' and the width to 'auto', the table will not automatically size to fill its containing block. However, once the calculated value of 'width' for the table is found (using the algorithms given below or, when appropriate, some other UA dependent algorithm) then the other parts of section 10.3 do apply. Therefore a table can be centered using left and right 'auto' margins, for instance.

div {
  display: table;
  margin: 0 auto;
}

div {
  display: table;
  margin: 0 auto;
  border: 2px solid blue;
}
span {
  display: inline-block;
  height: 20px;
  width: 20px;
  border: 2px solid red;
  margin: 10px;
}
<div>
  <span>1</span>
  <span>2</span>
</div>

但是,这可能不是必需的。你说你想让图像居中。因此,您可以使用 §16.2 text-align 将其内容居中,而不是尝试将 block 容器居中。 :

This property describes how inline-level content of a block container is aligned.

div {
  text-align: center;
}

div {
  text-align: center;
  border: 2px solid blue;
}
span {
  display: inline-block;
  height: 20px;
  width: 20px;
  border: 2px solid red;
  margin: 10px;
}
<div>
  <span>1</span>
  <span>2</span>
</div>

关于css - 边距:自动不居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30290381/

相关文章:

r - 确定绘图中文本的实际宽度

html - 删除元素的边距 "li"

css - IE6 中的奇怪边距

javascript - Canvas 中的额外边距

html - div 百分比不适用于父级

CSS:检测到错误的 body 尺寸..?

Jquery slidein 左右多个元素然后再次退出并循环

java - JTable 上的边距为 1px 边框

jquery - jquery 或 CSS 动态调整图像和文本大小以适应浏览器的宽度和/或高度并保持纵横比的功能?

css - 火狐浏览器.xul chrome : grey line added between toolbars and HTML content