- HTML 显示两个盒子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>常见的居中设置</title>
<link href="center.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="parent">
<div id="child">
<h1>hello world</h1>
<h1>世界你好</h1>
</div>
</div>
</body>
</html>
- CSS实现内部盒子居中
- 方法一:
外层div设置为相对定位;内部div设置为绝对定位,且设置left:50%;top:50%;(将盒子的左上角放在外部盒子的中心位置)transform:translate(-50%,-50%);(将盒子向左移动盒子宽度的50%,将盒子向上移动盒子高度的50%)——内部盒子完成居中
#parent{
position:relative;
background-color:orangered;
width:500px;
height:500px;
}
#child{
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
background-color:green;
}
- 方法二:
设置外部盒子为弹性盒子display:flex;
且盒子的每个子项垂直居中:align-items:center;
盒子的每个子项水平居中:justify-content:center;
#parent{
display:flex;
align-items:center;/*弹性盒子的每一个子项垂直居中*/
justify-content:center;/*弹性盒子的每个子项水平居中*/
width:500px;
height:500px;
background-color:orangered;
}
#child{
background-color:green;
}
- 效果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200420190228754.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1MzI3ODg2,size_16,color_FFFFFF,t_70)
以上是今天的收获。
文章思路来源于一个初次见面的老师。
希望对你有帮助。