要水平居中盒子,可以在其父容器上設(shè)置 text-align: center 屬性,具體步驟如下: 1. 為盒子設(shè)置 display: inline-block; 屬性。 2. 為盒子的父容器設(shè)置 text-align: center 屬性。
如何使用 CSS 讓盒子水平居中
直接回答:
要讓盒子水平居中,可以在其父容器上設(shè)置 text-align: center
屬性。
詳細(xì)說明:
要讓盒子水平居中,需要執(zhí)行以下步驟:
為盒子設(shè)置 display: inline-block;
屬性。 這將使盒子成為塊級(jí)元素,并允許對(duì)其進(jìn)行水平設(shè)置。
為盒子的父容器設(shè)置 text-align: center
屬性。 這將水平居中父容器中的所有塊級(jí)元素,包括盒子。
示例代碼:
<code class="<a style='color:#f60; text-decoration:underline;' href=" https: target="_blank">css">#parent { text-align: center; } #box { display: inline-block; }</code>
登錄后復(fù)制
應(yīng)用示例:
將以下 HTML 和 CSS 代碼添加到您的頁面:
HTML:
<code class="html"><div id="parent"> <div id="box">This box is centered horizontally.</div> </div></code>
登錄后復(fù)制
CSS:
<code class="css">#parent { text-align: center; } #box { display: inline-block; }</code>
登錄后復(fù)制
瀏覽器將水平居中帶有文本 “This box is centered horizontally.” 的盒子。