我想将一组并排排列的图像居中。尽管使用了 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.
但是,如果 width
是 auto
,这就没用了,因为这样 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/