定位与居中问题小结

今天写了一个div居中的练习,也遇到一些问题,这里想给大家总结一些经验。


定位与居中问题小结_第1张图片
定位与居中.png

这里主要总结居中问题,小圆的定位不讨论。

HTML





有两种方法进行水平与垂直居中。

第一种方法

html {
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
}
.box {
position: relative;
margin: 0 auto;
top: 50%;
margin-top: -100px;这个要在margin: 0 auto;后设置
width: 400px;
height: 200px;
background: #ccc;
}

必须设置html和body的宽高,不然top属性不起作用,因为不设置宽高body是没有高度的,relative是相对定位,父元素没有高度top属性就不起作用。
这种方法我个人觉得是比较好的一种,因为它没有第二种方法的缺点。

第二种方法

.box {
position: absolute;
top: 50%;
margin-top: -100px;
left: 50%;
margin-left: -200px;
width: 400px;
height: 200px;
background: #ccc;
}

这种方法有一个缺点,最小屏幕时左边的小圆偏移出去导致看不到。

两种方法的视情况使用,如果是设计图那种用第一个好,因为考虑了最小屏幕的情况。

全部代码:
** {
margin: 0;
padding: 0;
border: 0;
}
/第一种方法,必须设置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后设置/
width: 400px;
height: 200px;
background: #ccc;
}
不用以上方法,改用下面的方法居中会出现最小屏幕时左边的小圆偏移出去导致看不到
/第二种方法/
/.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;
}

你可能感兴趣的:(定位与居中问题小结)