大盒子用position:relative(相对定位),小盒子用position:absolute(绝对定位)
下图直接上了本次文章所用到的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
p{
text-align: center;
}
body{
padding: 0;
margin: 0;
box-sizing:border-box;
}
#all{
margin: 0 auto;
width: 960px;
height: 500px;
position: relative/*表示将all盒子设置为相对定位*/;
border: 1px springgreen solid;
}
#two{
width: 300px;
height: 230px;
position: absolute;
left: 5px;
top: 0px;
}
#three{
width: 350px;
height: 245px;
position: absolute;
left: 310px;
top: 0px;
}
#four{
width: 284px;
height: 250px;
line-height: 20px;
position: absolute;
top: 0px;
right: 5px;
}
#file{
position: absolute;
left: 5px;
top: 250px;
width: 660px;
height: 230px;
}
#sex{width: 217px;
height: 158px;
position: absolute;
top: 280px;
right: 25px;}
</style>
</head>
<body>
<div id="all">
<div id="two" style="background-color: cadetblue;">222</div>
<div id="three" style="background-color: darkkhaki;">333</div>
<div id="four" style="background-color: darkgreen;">444</div>
<div id="file" style="background-color: blue;">555</div>
<div id="sex" style="background-color: darkorange;">666</div>
</div>
<p>大盒子多为relative 小盒子多为absolute</p>
</body>
</html>
下图代码是html的body标签的基本框架
<body>
<div id="all">
<div id="two" style="background-color: cadetblue;">222</div>
<div id="three" style="background-color: darkkhaki;">333</div>
<div id="four" style="background-color: darkgreen;">444</div>
<div id="file" style="background-color: blue;">555</div>
<div id="sex" style="background-color: darkorange;">666</div>
</div>
<p>大盒子多为relative 小盒子多为absolute</p>
</body>
接下我们需要对body标签和#all的div盒子做出设置
body{
padding: 0;
margin: 0;
box-sizing:border-sizing
}
#all{
margin: 0 auto;
width: 960px;
height: 500px;
position: relative/*表示将all盒子设置为相对定位*/;
border: 1px springgreen solid;
}
- body标签是为了让css代码在其他浏览器显示时可以正常显示
- #all中使用position:relative;属性设置相对位置定位后,如果不设置top、left等属性的话,则元素本身不发生任何变化,与默认在标准流的位置不变。这里时将#all盒子固定下来,让其做盒子内元素的主先元素,为子元素的绝对定位做参考对象。
大盒子中的小盒子使用绝对定位【祖先元素的条件】
#two{
width: 300px;
height: 230px;
position: absolute;
left: 5px;
top: 0px;
}
- 绝对定位的重点时找到绝对定位的祖先元素,小盒子#two的祖先元素有#all body两个元素,
- 找祖先元素时要符合两个条件:一、是要最近的祖先元素。二、最近的祖先元素拥有定位属性#position
- 综上可以得出,#two小盒子的祖先元素是#all大盒子(使用了相对定位)
定位相关属性
position | 把元素放置在一个相对 的或者绝对的位置中,具体位置由top、left、right、bottom属性来定义。 |
---|---|
top | 设置定位元素的上边界与其包含块上边界之间的距离 |
right | |
bottom | |
left | |
overflow | 设置当元素内容溢出元素框时如何处理 |
clip | 设置绝对定位元素的形状,元素内容被剪入这个形状之中,可裁剪形状之外的区域 |
z-index | 设置绝对定位元素的堆叠顺序 |
tip:四个方向css属性是配合position定位元素的,只有当position属性设置为absolute、relative才有效,否则没有任何意义。
总结
1.当大盒子中的小盒子使用绝对定位的时候,里面的元素都会聚集在左上角,需要重新设置方向属性参数,以达到全部显示的效果