iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
0
Modern Web

從Stack Overflow學前端系列 第 3

從StackOverflow上學CODING(3)如何置中一個div

https://stackoverflow.com/questions/114543/how-to-horizontally-center-a-div
How to horizontally center a ?

大概是剛學CSS最常見的問題:
要如何置中一個html tag,如div
在stackoverflow上的#css 標籤類問題最多人想知道的排名 前十名內

先列出一個div包一個div

<div id="outer">  
  <div id="inner">Foo foo</div>
</div>

問答中簡潔的過濾很多最常用的方式:

1.最常見的margin 0 auto水平置中

#inner {
  margin: 0 auto;
}

2.利用inline-block的屬性 水平置中

#outer {
  width: 100%;
  text-align: center;
}


#inner {
  display: inline-block;
}

3.poistion並且四個方位都設定成0,margin:auto,其實跟第1個很像但是這個解法上下左右都會置中

#outer {
  position: relative;
}


#inner {
  margin: auto;  
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
}

4.再來就是 flexbox 常用的標準起手式

#outer {
    display: flex;
    justify-content: center;
    align-items: center;
}

剩下其他人還有提供另一些解法如box model等,但我認為上面四種最能被廣泛場景內使用的。


上一篇
從StackOverflow上學CODING(2)如何給字或背景一個透明背景
下一篇
從StackOverflow上學CODING(4)如何讓div或別的元素重疊
系列文
從Stack Overflow學前端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言