属性text-align: center;一个好方法来中心使用CSS图像?
img {
text-align: center;
}
属性text-align: center;一个好方法来中心使用CSS图像?
img {
text-align: center;
}
当前回答
实际上,代码的唯一问题是text-align属性应用于标记内的文本(是的,图像也算作文本)。你会想在图像周围放置一个span标签,并将其样式设置为text-align: center,如下所示:
跨度。centerImage { text-align:中心; } <span class="centerImage"><img src="http://placehold. "它/ 60/60 " / > < / span >
图像将居中。对于您的问题,这是最简单、最简单的居中图像的方法,只要您记得将该规则应用于图像的包含span(或div)。
其他回答
如果你正在使用一个带有图像的类,那么下面的步骤就可以了
class {
display: block;
margin: 0 auto;
}
如果它只是一个图像在一个特定的类,你想居中对齐,那么下面将做:
class img {
display: block;
margin: 0 auto;
}
我建议有三种方法来居中一个元素:
Using the text-align property .parent { text-align: center; } <div class="parent"> <img src="https://placehold.it/60/60" /> </div> Using the margin property img { display: block; margin: 0 auto; } <img src="https://placehold.it/60/60" /> Using the position property img { display: block; position: relative; left: -50%; } .parent { position: absolute; left: 50%; } <div class="parent"> <img src="https://placehold.it/60/60" /> </div>
第一种和第二种方法只在父元素至少和图像一样宽的情况下才有效。当图像比其父图像宽时,图像将不会保持居中!!
但是: 第三种方法是一个很好的方法!
这里有一个例子:
img { 显示:块; 位置:相对; 左:-50%; } .parent { 位置:绝对的; 左:50%; } < div class = "父" > <img src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/img_01.jpg" /> < / div >
使用这个到你的img CSS:
img {
margin-right: auto;
margin-left: auto;
}
我发现,如果我在一个div中有一个图像和一些文本,那么我可以使用text-align:center一次性对齐文本和图像。
HTML:
<div class="picture-group">
<h2 class="picture-title">Picture #1</h2>
<img src="http://lorempixel.com/99/100/" alt="" class="picture-img" />
<p class="picture-caption">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus sapiente fuga, quia?</p>
</div>
CSS:
.picture-group {
border: 1px solid black;
width: 25%;
float: left;
height: 300px;
#overflow:scroll;
padding: 5px;
text-align:center;
}
CodePen: https://codepen.io/artforlife/pen/MoBzrL?editors=1100
除非你需要支持旧版的ie浏览器。
现代的方法是在CSS中使用margin: 0 auto。
例如:http://jsfiddle.net/bKRMY/
HTML:
<p>Hello the following image is centered</p>
<p class="pic"><img src="https://twimg0-a.akamaihd.net/profile_images/440228301/StackoverflowLogo_reasonably_small.png"/></p>
<p>Did it work?</p>
CSS:
p.pic {
width: 48px;
margin: 0 auto;
}
这里唯一的问题是,段落的宽度必须与图像的宽度相同。如果你没有在段落上设置宽度,它将不起作用,因为它将假设100%并且你的图像将向左对齐,当然除非你使用text-align:center。
如果你喜欢,可以试试这把小提琴。