[問題] CSS的垂直、水平置中

看板Web_Design作者 (no anonymous)時間5年前 (2018/10/05 17:55), 編輯推噓5(5012)
留言17則, 9人參與, 5年前最新討論串1/1
我在網路上GOOGLE能夠在視窗內,水平和垂直方向都置中的表單: 例如以下: https://jsfiddle.net/lueichun/bq92w7oa/1/ 一開始是<body>下一層的div(<div class="back">) 這個div的css是: .back { background: #e2e2e2; width: 100%; /* height:100%;*/ position: absolute; top: 0; bottom: 0; } 這樣可以讓這div填滿整個body。我的理解是: 將該div的position設成absolute,就可讓該div的位置相對於body, 然後設定top、bottom都=0,即可讓該div的位置,相對於body,頂端跟底端都是重疊的。 而設定width=100%,則讓該div橫跨整個body。 這樣該div就和body重疊,也就填滿body了。 然後設定再下一層的div(<div class="div-center">): .div-center { width: 600px; height: 400px; background-color: #fff; position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; } 我想說上一個div是利用position: absolute;top: 0;bottom: 0; 就能設定跟body相對的位置。 那我這邊如果只單純設定position,以及left=0、right=0等值, 該div卻位在左上角,看起來right=0、bottom=0沒有作用。 非得要將上margin=auto,整個div才會置中。 請問如果只是單純設定position、left、right、top這些屬性,為何在這個div就失效呢? 而且margin=auto不是用來設定水平方向置中而已嗎? 為何在這邊也會影響垂直方向置中呢? 感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.167.48.218 ※ 文章網址: https://www.ptt.cc/bbs/Web_Design/M.1538733336.A.C56.html

10/05 18:33, 5年前 , 1F
有設寬跟高,同時又設left:0 以及right :0時,規則會有衝
10/05 18:33, 1F

10/05 18:33, 5年前 , 2F
突,只會有left 和寬的屬性有作用。
10/05 18:33, 2F

10/05 19:24, 5年前 , 3F
先搞清楚top bottom right left是做什麼的吧
10/05 19:24, 3F

10/05 19:25, 5年前 , 4F
這個要絕對定位就top:50% left:50% 然後transform
10/05 19:25, 4F

10/05 19:27, 5年前 , 5F
然後margin只有一個參數是把上下左右都設一樣的值
10/05 19:27, 5F

10/05 19:28, 5年前 , 6F
只要水平居中應該是margin:0 auto;
10/05 19:28, 6F

10/06 19:07, 5年前 , 7F
position預設是static,此時你left、top那些都沒用
10/06 19:07, 7F

10/06 19:09, 5年前 , 8F
margin:0 auto;才是水平置中而已 0是指上下margin設成0
10/06 19:09, 8F

10/06 19:10, 5年前 , 9F
auto指根據父容器自動調整左右margin都一樣,導致置中
10/06 19:10, 9F

10/06 19:13, 5年前 , 10F
效果,margin:auto;指根據父容器調整上下margin一樣,
10/06 19:13, 10F

10/06 19:13, 5年前 , 11F
左右margin也一樣,所以才會有水平和垂直置中的效果。
10/06 19:13, 11F

10/07 13:08, 5年前 , 12F
要不要改試height: vh100
10/07 13:08, 12F

10/09 23:26, 5年前 , 13F
Flexbox 好用
10/09 23:26, 13F

10/14 21:19, 5年前 , 14F
會用Flex真的能拯救你(拍
10/14 21:19, 14F

10/19 21:39, 5年前 , 15F
為什麼不用flex去設定
10/19 21:39, 15F

10/30 00:13, 5年前 , 16F
推flex
10/30 00:13, 16F

11/04 12:39, 5年前 , 17F
flex會幫你自動調整喔
11/04 12:39, 17F
文章代碼(AID): #1RjpKOnM (Web_Design)