文章链接:
实验室分享–float
实验室分享–居中对齐
实验室分享–伪类、伪元素
实验室分享–display:flex
一、盒子垂直居中
1、display:flex;
- Flex意为”弹性布局”,用来为盒状模型提供最大的灵活性。任何一个容器都可以指定为Flex布局。(行内也可以,inline-block)。
- 采用Flex布局的元素,称为 ”容器”。它的所有子元素成为容器成员,称为 ”项目”。
- 容器默认存在两根轴:水平的主轴 和 垂直的交叉轴
这里用到的是两个属性:
(1)justify-content: center:-------定义了项目在主轴上的对齐方式。
(2)align-items:center:-----------定义项目在交叉轴上如何对齐。
代码:
//html
<div class="Center">
<p>d第一种</p>
</div>
//css
.Center{
background-color: #800070;
width: 100%;
height:500px;
display: flex;
justify-content: center;
align-items:center;
}
.Center p{
width: 200px;
height: 200px;
background-color: deeppink;
line-height: 200px;
text-align: center;
}
2、transform:translate(-50%,-50%);
往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置。
代码:
//html
<div class="Center">
<p>第一种</p>
</div>
//css
*{
margin:0;
padding:0;
}
.Center{
background-color: dimgrey;
width: 100%;
height: 500px;
position: relative;
}
.Center p {
position: absolute;
width: 200px;
height: 200px;
background-color:darkorange;
line-height: 200px;
text-align: center;
left: 50%;
top: 50%;
/*margin-top:-100px;
margin-left:-100px;*/
transform:translate(-50%,-50%);
}
3、display: table-cell;
//html
<div id="div1">
<div id="div2"></div>
</div>
//css
#div1{
width: 200px;
height: 200px;
display: table-cell;
vertical-align: middle;/*使当前元素内的内容上下居中*/
background: white;
}
#div2{
width:50px;
height:50px;
background-color: pink;
margin:0 auto;
]}
二、文本居中
1、父元素设置display:table;子元素设置display:table-cell;
//html
<div>
<p>
hello world <br />
hello world <br />
hello world <br />
hello world
</p>
</div>
//css
div{
display: table;
text-align: center;
background: #fff;
}
p{
display: table-cell;
vertical-align: middle;
width: 500px;
height: 200px;
}
文章链接:
实验室分享–float
实验室分享–居中对齐
实验室分享–伪类、伪元素
实验室分享–display:flex