今天寫了一個div居中的練習(xí),也遇到一些問題,這里想給大家總結(jié)一些經(jīng)驗(yàn)。
這里主要總結(jié)居中問題,小圓的定位不討論。
HTML
<code><body>
<div class="box">
<div class="upleft"></div>
<div class="downright"></div>
</div>
</body></code>
有兩種方法進(jìn)行水平與垂直居中虱颗。
第一種方法
<code>html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
}
.box {
position: relative;
margin: 0 auto;
top: 50%;
margin-top: -100px;這個要在margin: 0 auto;后設(shè)置
width: 400px;
height: 200px;
background: #ccc;
}</code>
必須設(shè)置html和body的寬高宣赔,不然top屬性不起作用,因?yàn)椴辉O(shè)置寬高body是沒有高度的,relative是相對定位,父元素沒有高度top屬性就不起作用华蜒。
這種方法我個人覺得是比較好的一種,因?yàn)樗鼪]有第二種方法的缺點(diǎn)。
第二種方法
<code>.box {
position: absolute;
top: 50%;
margin-top: -100px;
left: 50%;
margin-left: -200px;
width: 400px;
height: 200px;
background: #ccc;
}</code>
這種方法有一個缺點(diǎn)舌劳,最小屏幕時左邊的小圓偏移出去導(dǎo)致看不到客们。
兩種方法的視情況使用,如果是設(shè)計圖那種用第一個好沸手,因?yàn)榭紤]了最小屏幕的情況契吉。
全部代碼:
<code>** {
margin: 0;
padding: 0;
border: 0;
}
/第一種方法菲语,必須設(shè)置html和body的寬高潭辈,不然top屬性不起作用/
html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
}
.box {
position: relative;
margin: 0 auto;
top: 50%;
margin-top: -100px;/這個要在margin后設(shè)置/
width: 400px;
height: 200px;
background: #ccc;
}
不用以上方法婶恼,改用下面的方法居中會出現(xiàn)最小屏幕時左邊的小圓偏移出去導(dǎo)致看不到
/第二種方法/
/.box {
position: absolute;
top: 50%;
margin-top: -100px;
left: 50%;
margin-left: -200px;
width: 400px;
height: 200px;
background: #ccc;
}/
.upleft, .downright {
width: 50px;
height: 50px;
background: #fc0;
}
.upleft {
position: absolute;
left: 0;
top: 0;
border-bottom-right-radius: 50px;
}
.downright {
position: absolute;
right: 0;
bottom: 0;
border-top-left-radius: 50px;
}