在 css 中,可通过以下方法让图像居中:使用文本对齐属性:将图像设置为块元素,并设置自动左右外边距。使用 flexbox 布局:将图像放入 flexbox 容器,并设置水平和垂直居中属性。使用网格布局:将图像放入网格容器,并设置同时水平和垂直居中属性。使用绝对定位:将图像从正常流中移除,设置水平居中位置和通过变换使其垂直居中。
CSS 中如何让图像居中
在 CSS 中,让图像居中可以使用多种方法:
使用文本对齐属性
<code class="<a style='color:#f60; text-decoration:underline;' href=" https: target="_blank">css">img {
display: block;
margin: 0 auto;
}</code>
登录后复制
display: block 使图像成为一个块元素。
margin: 0 auto 自动设置图像的左右外边距,使其在父元素中水平居中。
使用 flexbox 布局
<code class="css">.container {
display: flex;
justify-content: center;
align-items: center;
}
img {
width: 100px;
height: 100px;
}</code>
登录后复制
创建一个 flexbox 容器(.container)。
justify-content: center 将子元素(图像)在水平方向上居中。
align-items: center 将子元素在垂直方向上居中。
使用网格布局
<code class="css">.container {
display: grid;
place-items: center;
}
img {
width: 100px;
height: 100px;
}</code>
登录后复制
创建一个网格容器(.container)。
place-items: center 将子元素(图像)同时在水平和垂直方向上居中。
使用绝对定位
<code class="css">img {
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
}</code>
登录后复制
使用绝对定位将图像从其正常流中移除。
left: 50% 将图像水平居中,但它将相对于其父元素的左边界居中。
transform: translate(-50%, -50%) 将图像向左和向上移动其自身宽高的 50%,从而在父元素中居中。






