使用 css 實(shí)現(xiàn)整體居中:設(shè)置 align-items: center 進(jìn)行垂直居中。設(shè)置 justify-content: center 進(jìn)行水平居中。同時(shí)設(shè)置 align-items 和 justify-content 屬性可將整體居中。
如何使用 CSS 設(shè)置整體居中
在網(wǎng)頁(yè)設(shè)計(jì)中,有時(shí)需要將所有內(nèi)容居中對(duì)齊,這可以通過(guò)使用 CSS 的 align-items 和 justify-content 屬性來(lái)實(shí)現(xiàn)。
align-items 屬性
align-items 屬性用于設(shè)置容器中項(xiàng)目(flex item)的垂直對(duì)齊方式。如果將 align-items 設(shè)置為 center,則項(xiàng)目將垂直居中:
<code class="<a style='color:#f60; text-decoration:underline;' href=" https: target="_blank">css">.container { display: flex; align-items: center; }</code>
登錄后復(fù)制
justify-content 屬性
justify-content 屬性用于設(shè)置容器中項(xiàng)目(flex item)的水平對(duì)齊方式。如果將 justify-content 設(shè)置為 center,則項(xiàng)目將水平居中:
<code class="css">.container { display: flex; justify-content: center; }</code>
登錄后復(fù)制
將整體居中
要將整體居中,需要同時(shí)設(shè)置 align-items 和 justify-content 屬性:
<code class="css">.container { display: flex; align-items: center; justify-content: center; }</code>
登錄后復(fù)制
示例
以下示例演示了如何使用 CSS 將網(wǎng)頁(yè)中的所有內(nèi)容居中:
<code class="html"> <style> body { display: flex; align-items: center; justify-content: center; height: 100vh; } </style> <h1>Hello, world!</h1> </code>
登錄后復(fù)制