字数
611 字
阅读时间
3 分钟
两栏布局
左栏固定宽度,右栏撑满
实现要考虑两个点:
- 右边和左边的距离保持
- 右边如何撑满
float: left 和 width: auto + margin-left
css
.outer {
height: 100px;
}
.left {
float: left;
width: 200px;
background: tomato;
}
.right {
margin-left: 200px;
width: auto;
background: gold;
}float: left 和 overflow: hidden
css
.left{
width: 100px;
height: 200px;
background: red;
float: left;
}
.right{
height: 300px;
background: blue;
overflow: hidden;
}右边形成 BFC,BFC 不会与 float 发生重叠
display: flex 和 flex: 1
绝对定位
css
/* 左边栏设置 */
.outer {
position: relative;
height: 100px;
}
.left {
position: absolute;
width: 200px;
height: 100px;
background: tomato;
}
.right {
margin-left: 200px;
background: gold;
}
/* 右边栏设置 */
.outer {
position: relative;
height: 100px;
}
.left {
width: 200px;
background: tomato;
}
.right {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 200px;
background: gold;
}三栏布局
absolute 和 margin-left+margin-right
display: flex 和 flex: 1
float: left + float: right 和 margin-left + margin-right
中间一栏必须放到最后
盒子模型实现水平垂直居中
未知宽高
绝对定位 + translate
css
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}当使用:top: 50%;left: 50%;, 是以左上角为原点,故不处于中心位置
translate(-50%,-50%) 函数作用是,往上(x 轴),左(y 轴)移动自身长宽的 50%,以使其居于中心位置
使用 flex 布局
已知宽高
绝对定位 + margin
css
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}利用绝对定位,设置四个方向的值都为 0,并将 margin 设置为 auto,由于宽高固定,因此对应方向实现平分,可以实现水平和垂直方向上的居中
flex 及 flex-wrap 最后一行元素样式
预期效果:一行四列,每个元素有固定的 margin 间距,4n 处消除右边距,最后一行去除下边距,目的是不影响外层容器的布局
css
.list {
display: flex;
flex-wrap: wrap;
}
.item {
margin: 0 24px 24px 0;
// 最右边一列元素消除右边距
&:nth-child(4n) {
margin-right: 0;
}
// 最后一排第一个元素下边距为 0
&:nth-child(4n+1):nth-last-child(-n+4) {
margin-bottom: 0;
}
// 最后一排第一个元素之后的相邻元素下边距为 0
&:nth-child(4n+1):nth-last-child(-n+4)~.item {
margin-bottom: 0;
}
}- 伪类选择器的从属关系是 右边 > 左边
: nth-last-child( <nth> [ of <complex-selector-list> ]? )
![[css选择器#读取规则]]