使用文字对齐中心使图片居中?

本文详细介绍了使用CSS实现图像在网页中水平和垂直居中的多种方法,包括利用text-align、绝对定位、span标签包裹和块级显示等技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自: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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值