准备以后每天分享一两个知识点,一方面方便自己复习,另一方面转移一下笔记。
第一天先从css居中开始:
一.宽高固定
1.绝对定位+margin:auto
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin:auto;
//盒子大小不确定,被内容撑开时,这么写不行会把视角撑满
2.绝对定位+负margin
// 涉及到具体的px,因此不太推荐使用
.box {
width: 200px;
height: 200px;
background: green;
position: relative;
}
.child {
width: 100px;
height: 100px;
background: yellow;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
3.绝对定位+transform
//该方式是我最常用的,是个万能居中方案,不管有没有宽高都可以居中
.box {
width: 200px;
height: 200px;
background: green;
position: relative;
}
.child {
/*
width: 100px;
height: 100px;
*/
position: absolute;
/*原理: 绝对定位元素是相对于包含块进行定位的 平移是相对于自己平移的 */
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
/*此时不管内容是什么,盒子都居中*/
}
4.flex布局
//很常用
.box {
width: 200px;
height: 200px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child {
background: yellow;
height: 100px;
width: 100px;
}
5.网格布局
// 对网格布局不太熟悉的话看一下菜鸟的文档复习一下
.box {
width: 200px;
height: 200px;
border: 1px solid red;
display: grid;
}
.child {
width: 100px;
height: 100px;
background: yellow;
margin: auto;
}
二.不定宽高
1.绝对定位 + transform
// 上面已经说过这个是万能居中的方案
.box {
width: 200px;
height: 200px;
position: relative;
}
.child {
position: absolute;
background: yellow;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2.flex布局
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
align-items: center; // 纵轴对齐方式,默认是纵轴 子元素垂直居中
justify-content: center; //纵轴对齐方式,默认是纵轴
}
.child {
background: red;
}
或者给子元素设置margin:auto
.box {
width: 200px;
height: 200px;
border: 1px solid;
display: flex;
}
.child {
background: red;
margin: auto; // 水平垂直居中
}