下面是兩種常見的居中解決方案。
一種用于垂直對(duì)齊的彈性項(xiàng)目(flex-direction: column
),另一種用于水平對(duì)齊的彈性項(xiàng)目(flex-direction: row
)。
在這兩種情況下,居中的div的高度可以是可變的,未定義的,未知的,不重要。
以下是兩者的HTML代碼:
<div id="container"><!-- flex容器 --> <div class="box" id="bluebox"><!-- flex項(xiàng)目 --> <p>DIV #1</p> </div> <div class="box" id="redbox"><!-- flex項(xiàng)目 --> <p>DIV #2</p> </div> </div>
CSS(不包括裝飾樣式)
當(dāng)彈性項(xiàng)目垂直堆疊時(shí):
#container { display: flex; /* 建立flex容器 */ flex-direction: column; /* 將主軸設(shè)置為垂直方向 */ justify-content: center; /* 在這種情況下,垂直居中項(xiàng)目 */ align-items: center; /* 在這種情況下,水平居中項(xiàng)目 */ height: 300px; } .box { width: 300px; margin: 5px; text-align: center; /* 將文本在<p>中居中,<p>不是flex項(xiàng)目 */ }
當(dāng)彈性項(xiàng)目水平堆疊時(shí):
調(diào)整上面代碼中的flex-direction
規(guī)則。
#container { display: flex; flex-direction: row; /* 將主軸設(shè)置為水平方向(默認(rèn)設(shè)置) */ justify-content: center; /* 在這種情況下,水平居中項(xiàng)目 */ align-items: center; /* 在這種情況下,垂直居中項(xiàng)目 */ height: 300px; }
彈性格式化上下文的范圍僅限于父子關(guān)系。超出子代的彈性容器的后代不參與彈性布局,并將忽略彈性屬性?;旧希瑥椥詫傩栽谧哟獠豢衫^承。
因此,您始終需要將display: flex
或display: inline-flex
應(yīng)用于父元素,以便將彈性屬性應(yīng)用于子元素。
為了垂直和/或水平居中文本或其他內(nèi)容,使項(xiàng)目成為(嵌套的)彈性容器,并重復(fù)居中規(guī)則。
.box { display: flex; justify-content: center; align-items: center; /* 對(duì)于單行彈性容器 */ align-content: center; /* 對(duì)于多行彈性容器 */ }
更多細(xì)節(jié)請(qǐng)參見:如何在flexbox中垂直對(duì)齊文本?
或者,您可以將margin: auto
應(yīng)用于彈性項(xiàng)目的內(nèi)容元素。
p { margin: auto; }
在這里了解有關(guān)彈性auto
邊距的更多信息:對(duì)齊彈性項(xiàng)目的方法(參見box#56)。
當(dāng)彈性容器有多行(由于換行)時(shí),align-content
屬性將對(duì)交叉軸對(duì)齊至關(guān)重要。
來自規(guī)范:
更多細(xì)節(jié)請(qǐng)參見:flex-wrap如何與align-self,align-items和align-content一起工作?
所有主要瀏覽器都支持Flexbox,除了IE < 10。一些最近的瀏覽器版本,如Safari 8和IE10,需要供應(yīng)商前綴。為了快速添加前綴,可以使用Autoprefixer。更多詳細(xì)信息請(qǐng)參見這個(gè)答案。
有關(guān)使用CSS表格和定位屬性的替代居中解決方案,請(qǐng)參見此答案:https://stackoverflow.com/a/31977476/3597276
我認(rèn)為你想要的是以下內(nèi)容。
html, body { height: 100%; } body { margin: 0; } .flex-container { height: 100%; padding: 0; margin: 0; display: flex; align-items: center; justify-content: center; } .row { width: auto; border: 1px solid blue; } .flex-item { background-color: tomato; padding: 5px; width: 20px; height: 20px; margin: 10px; line-height: 20px; color: white; font-weight: bold; font-size: 2em; text-align: center; }
<div class="flex-container"> <div class="row"> <div class="flex-item">1</div> <div class="flex-item">2</div> <div class="flex-item">3</div> <div class="flex-item">4</div> </div> </div>