在 css 中,可通過(guò)以下方法讓圖像居中:使用文本對(duì)齊屬性:將圖像設(shè)置為塊元素,并設(shè)置自動(dòng)左右外邊距。使用 flexbox 布局:將圖像放入 flexbox 容器,并設(shè)置水平和垂直居中屬性。使用網(wǎng)格布局:將圖像放入網(wǎng)格容器,并設(shè)置同時(shí)水平和垂直居中屬性。使用絕對(duì)定位:將圖像從正常流中移除,設(shè)置水平居中位置和通過(guò)變換使其垂直居中。
CSS 中如何讓圖像居中
在 CSS 中,讓圖像居中可以使用多種方法:
使用文本對(duì)齊屬性
<code class="<a style='color:#f60; text-decoration:underline;' href=" https: target="_blank">css">img { display: block; margin: 0 auto; }</code>
登錄后復(fù)制
display: block
使圖像成為一個(gè)塊元素。
margin: 0 auto
自動(dòng)設(shè)置圖像的左右外邊距,使其在父元素中水平居中。
使用 flexbox 布局
<code class="css">.container { display: flex; justify-content: center; align-items: center; } img { width: 100px; height: 100px; }</code>
登錄后復(fù)制
創(chuàng)建一個(gè) flexbox 容器(.container
)。
justify-content: center
將子元素(圖像)在水平方向上居中。
align-items: center
將子元素在垂直方向上居中。
使用網(wǎng)格布局
<code class="css">.container { display: grid; place-items: center; } img { width: 100px; height: 100px; }</code>
登錄后復(fù)制
創(chuàng)建一個(gè)網(wǎng)格容器(.container
)。
place-items: center
將子元素(圖像)同時(shí)在水平和垂直方向上居中。
使用絕對(duì)定位
<code class="css">img { position: absolute; left: 50%; transform: translate(-50%, -50%); }</code>
登錄后復(fù)制
使用絕對(duì)定位將圖像從其正常流中移除。
left: 50%
將圖像水平居中,但它將相對(duì)于其父元素的左邊界居中。
transform: translate(-50%, -50%)
將圖像向左和向上移動(dòng)其自身寬高的 50%,從而在父元素中居中。