close

水平置中

text-align: center;

文字置中

屬性內的內容置中

1
text-align: center;

範例

 

margin : 0 auto;

區塊置中

用來控制帶有寬度的屬性,使其屬性可在瀏覽器中置中 ( 屬性 ex: <div> )

1
margin : 0 auto;

範例

 

display: flex;    Flexbox 的方法

justify-content: center; 水平置中

使屬性內的屬性置中( 屬性 ex: <div> )

=要置中的屬性的外層 CSS 裡 ( 範例 置中兩個div,最外層 wrap 寫上css )

1
2
display: flex;
justify-content: center;

範例

See the Pen Flex justify-content: cneter; 水平置中 by ccc6504 (@cdpro2) on CodePen.

 

垂直置中

line-height: (子屬為文字標籤)

設定行高,將子屬line-height設定與外層屬性的高度一樣,就能垂直置中,缺點只能有一行,多行會跑版

1
2
3
4
5
6
#app{
  height: 100px;
}
#app h1{
  line-height: 100px;
}

範例 ( 範例中 app2 ,多了一行 <p>,所以會跑版

或是要將內容裡的區塊屬性<div>置中區塊內容屬性要給 display: inline-block;

1
2
3
4
5
6
7
#app{
  height: 200px;
  line-height: 225px; /*200 + (red:50/2)*/
}
#app-red{
  height: 50px;
}

範例 ( 範例中 外層屬性多給了 line-height: 225px;  ,是 #app-red的高度 /2  再加上 line-height 200+25 )

 

display: flex;    Flexbox 的方法

align-items: center;  垂直置中(並排)

使屬性內的屬性垂直置中( 屬性 ex: <div> )

=要置中的屬性的外層,給高度(height)& CSS ( 範例 置中兩個div,最外層 wrap 寫上 高度 & 置中的css )

1
2
3
4
5
#wrap{
  display: flex;
  align-items: center;
  height: 500px; /* 要給高度 */
}

範例

align-items: center;  垂直置中(多行)

變成多行置中,要置中的對象與外層之間再加上一層框 ( 範例 外層(wrap) 與 兩個div 之間 加入一個div(id="cont" ) 

1
2
3
<div id="wrap">
    <div id="cont"> <!-- 多這層 -->
        <div id="app">

範例

arrow
arrow
    文章標籤
    html css
    全站熱搜

    Aha 發表在 痞客邦 留言(0) 人氣()