属性text-align: center;一个好方法来中心使用CSS图像?
img {
text-align: center;
}
属性text-align: center;一个好方法来中心使用CSS图像?
img {
text-align: center;
}
当前回答
你可以在父元素上使用text-align: center,并将img更改为display: inline-block→,因此它的行为就像一个文本元素,如果父元素有宽度,它将居中!
img {
display: inline-block
}
其他回答
你可以在父元素上使用text-align: center,并将img更改为display: inline-block→,因此它的行为就像一个文本元素,如果父元素有宽度,它将居中!
img {
display: inline-block
}
我发现,如果我在一个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
实际上,代码的唯一问题是text-align属性应用于标记内的文本(是的,图像也算作文本)。你会想在图像周围放置一个span标签,并将其样式设置为text-align: center,如下所示:
跨度。centerImage { text-align:中心; } <span class="centerImage"><img src="http://placehold. "它/ 60/60 " / > < / span >
图像将居中。对于您的问题,这是最简单、最简单的居中图像的方法,只要您记得将该规则应用于图像的包含span(或div)。
如果你的img元素在一个div中,它本身在另一个div中,它的显示被设置为flexbox,就像我这里的例子: (HTML)
<nav class="header">
<div class="image">
<img
src=troll
alt="trollface"
></img>
</div>
<div class="title">
Meme Generator
</div>
<div class="subtitle">
React Course - Project 3
</div>
</nav>
(CSS)
.header{
display: flex;
}
.image{
width: 5%;
height: 100%;
}
.image > img{
width: 100%;
}
你可以这样设置你的。image div垂直对齐:
.image{
width: 5%;
height: 100%;
align-self: center;
}
使用这个到你的img CSS:
img {
margin-right: auto;
margin-left: auto;
}