本文翻译自:Center image using text-align center?
Is the property text-align: center;
该属性是否为text-align: center;
a good way to center an image using CSS? 用CSS将图像居中的好方法?
img {
text-align: center;
}
#1楼
参考:https://stackoom.com/question/TbQf/使用文字对齐中心使图片居中
#2楼
I came across this post , and it worked for me: 我碰到了这篇文章 ,它对我有用:
img { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; }
<div style="border: 1px solid black; position:relative; min-height: 200px"> <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a"> </div>
(Vertical and horizontal alignment) (垂直和水平对齐)
#3楼
Actually, the only problem with your code is that the text-align
attribute applies to text (yes, images count as text) inside of the tag. 实际上,代码的唯一问题是text-align
属性适用于标记内的文本(是的,图像算作文本)。 You would want to put a span
tag around the image and set its style to text-align: center
, as so: 您可能希望在图像周围放置一个span
标签,并将其样式设置为text-align: center
,如下所示:
span.centerImage { text-align: center; }
<span class="centerImage"><img src="http://placehold.it/60/60" /></span>
The image will be centered. 图像将居中。 In response to your question, it is the easiest and most foolproof way to center images, as long as you remember to apply the rule to the image's containing span
(or div
). 回答您的问题,这是居中图像的最简单,最简单的方法,只要您记得将规则应用于图像的包含span
(或div
)即可。
#4楼
另一种方法是将一个封闭的段落居中:
<p style="text-align:center; border:1px solid black"><img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a"></p>
#5楼
Simply change parent align :) 只需更改父对齐:)
Try this one on parent properties: 在父属性上尝试以下一项:
text-align:center
#6楼
If you are using a class with an image then the following will do 如果您正在使用带有图像的类,则将执行以下操作
class {
display: block;
margin: 0 auto;
}
If it is only an image in a specific class that you want to center align then following will do: 如果只是要对齐的特定类别中的图像,则可以执行以下操作:
class img {
display: block;
margin: 0 auto;
}