纵向 margin 重叠
两个元素都有设置margin的情况下,两个元素之间的距离为那个margin较大的值
relative
设置top、bottom、left、right是相对于元素自身原来的位置而言
absolute
- absolute 元素脱离了文档结构,会产生破坏性,导致父元素坍塌。
- absolute 元素位置并没有发生变化,还是在它原本的位置
- absolute 元素会悬浮在页面上方,会挡住下方的内容
水平居中
- inline 元素用text-align: center;
.container { text-align: center;}
- block 元素可使用margin: auto;
.item {
width: 1000px;
margin: auto;
}
- 绝对定位元素结合left和margin实现,但是必须知道宽度。
.container {
position: relative;
width: 500px;
}
.item {
width: 300px;
height: 100px;
position: absolute;
left: 50%;
margin: -150px;
}
垂直居中
- inline 元素可设置line-height的值等于height值
.container {
height: 50px;
line-height: 50px;
}
- 绝对定位元素,可结合left和margin实现,但是必须知道尺寸
.container {
position: relative;
height: 200px;
}
.item {
width: 80px;
height: 40px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -20px;
margin-left: -40px;
}
- 也可以结合transform实现居中,不需要知道尺寸,兼容性不好
.container {
position: relative;
height: 200px;
}
.item {
width: 80px;
height: 40px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: blue;
}
- 绝对定位结合margin: auto,不需要提前知道尺寸,兼容性好。
.container {
position: relative;
height: 300px;
}
.item {
width: 100px;
height: 50px;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin: auto;
}
flex布局
.container {
display: flex;
flex-direction: column-reverse| column | row | row-reverse; 设置元素是水平排列,还是垂直排列
justify-content: flex-start | flex-end | center | space-between | space-around; 水平方向设置元素左对齐,右对齐,还是居中...
align-items: flex-start | flex-end | center | baseline | stretch; 垂直方向设置元素上对齐,下对齐,还是居中...
}
.item {
flex: 1;设置元素所占位置的大小
}
网友评论