目录
1. 定宽高
适用于块级元素
1.1 父相子绝 + left top: 父元素宽高/2 + margin: -width/2
父相子绝表示子元素相对父元素移动
left top的百分比是相对于父级元素的宽 高
left top父元素宽高一半表示相对父元素向右向下移动父元素的一半,此时相对移动的点是子元素左上角的点
负外边距表示把子元素中心点移到子元素左上角点的位置(即父元素中心点)
.father{
height: 400px;
width: 400px;
background-color: beige;
position: relative;
}
.son{
height: 200px;
width: 200px;
background-color:yellow;
position: absolute;
left: 50%;
top: 50%;
margin: -100px 0 0 -100px;
}
1.2 父相子绝 + top bottom right left:0 (上下、左右各相等) + margin:auto
.father{
height: 400px;
width: 400px;
background-color: beige;
position: relative;
}
.son{
height: 200px;
width: 200px;
background-color:yellow;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
2 不定宽高(都是CSS3)
2.1 设置transform属性的translate值
transform属性允许将元素旋转,缩放,移动,倾斜
translate(x,y)的百分比是相对于元素自身的,这种方法对应于定宽高的第一种方法
.father{
height: 400px;
width: 400px;
background-color: beige;
position: relative;
}
.son{
height: 200px;
width: 200px;
background-color:yellow;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
2.2 设置父元素flex(弹性)布局
align-items是纵轴的对齐方式
justify-content是横轴的对齐方式
.father{
height: 400px;
width: 400px;
background-color: beige;
display: flex;
justify-content: center;
align-items: center;
}
.son{
height: 200px;
width: 200px;
background-color:yellow;
}
2.3 设置父元素grid(网格)布局
align-self是子元素一个单元格内纵轴上的对齐方式
justify-self是子元素一个单元格内横轴上的对齐方式
.father{
height: 400px;
width: 400px;
background-color: beige;
display: grid;
}
.son{
height: 200px;
width: 200px;
background-color:yellow;
justify-self: center;
align-self: center;
}