《定位布局》
目录
一、position定位
四方位
- top:相对上边界偏移量;
- bottom:相对下边界偏移量;
- left:相对左边界偏移量;
- right:相对右边界偏移量。
层调整
- z-index:当元素重叠时,使用该属性进行层序调整。
静态定位(static)
元素默认定位方式。
相对定位(relative)
相对自身位置定位。
- html
<div class="outer1">
<div class="inner1"></div>
</div>
- css
.outer1 {
width: 300px;
height: 300px;
margin: 100px auto;
background-color: lightblue;
}
.inner1 {
width: 100px;
height: 100px;
background-color: lightgreen;
/* 相对自身四个边进行定位 */
position: relative;
right: 20px;
bottom: 20px;
}
绝对定位(absolute)
相对父元素位置进行定位,前提是父元素必须先定位。
- html
<div class="outer2">
<div class="inner2"></div>
</div>
- css
.outer2 {
width: 300px;
height: 300px;
margin: 100px auto;
background-color: lightblue;
/* 父元素先定位 */
position: relative;
}
.inner2 {
width: 100px;
height: 100px;
background-color: lightgreen;
/* 相对父元素四个边进行定位 */
position: absolute;
right: 20px;
bottom: 20px;
}
</style>
固定定位(fixed)
相对浏览器进行定位。
- html
<div class="outer3">
<div class="inner3"></div>
</div>
- css
.outer3 {
width: 300px;
height: 300px;
margin: 100px auto;
background-color: lightblue;
}
.inner3 {
width: 100px;
height: 100px;
background-color: lightgreen;
/* 相对浏览器四个边进行定位 */
position: fixed;
right: 20px;
bottom: 100px;
}
二、Flex布局
Flex是FlexibleBox的缩写,意为"弹性布局",用来为盒状模型提供最大的灵活性。
- html
<div class="box">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
- css
.box {
width: 800px;
height: 40px;
margin: 30px auto;
text-align: center;
line-height: 40px;
/* flex弹性布局*/
display: flex;
/* 布局方向:
* row(横向从左到右),
* row-reverse(横向从右到左),
* column(纵向从上到下),
* column-reverse(纵向从下到上)
*/
flex-direction: column-reverse;
/* 对齐方式:
* flex-start(默认值):左对齐
* flex-end:右对齐
* center: 居中
* space-between:两端对齐,项目之间的间隔都相等。
* space-around:每个项目两侧的间隔相等。所以,项目之间的间隔比项目与边框的间隔大一倍。
*/
justify-content: space-between;
}
.box div {
width: 120px;
height: 40px;
background-color: lightblue;
border-radius: 5px;
}
总结
重点
- 相对定位、绝对定位、固定定位;
- 弹性布局的使用方式。
难点
- 相对定位、绝对定位、固定定位;
- 弹性布局的使用方式。