css实现水平居中

代码示例

复制代码
<div class="box">
	<div class="box1"></div>
</div>

1.弹性布局:(推荐)

display:flex;
这些要添加在父级的,是父级的属性

//父级添加display:flex;

//父级添加justify-content:center;

复制代码
.box{
 	width: 500px;
 	height: 300px;
 	background-color: aquamarine;
 	display: flex;
 	/*主轴-x轴:居中*/
 	justify-content: center;
}
.box1{
 	width: 200px;
 	height: 100px;
 	background-color: lightpink;
}

效果图:

2.添加margin值auto

外边距可以让块级盒子水平居中,但是必须满足两个条件:

①盒子必须指定了宽度

②盒子左右的外边距都设置为auto
.header{

width:960px;

margin:0 auto;

}
以上方法是让块级元素水平居中,行内元素或者行内块元素水平居中给其父元素添加text-ali gn:center;

复制代码
 .box{
 	width: 500px;
 	height: 300px;
 	background-color: aquamarine;
 	
}
.box1{
 	width: 200px;
 	height: 100px;
 	background-color: lightpink;
    margin: 0 auto;
}

3.text-align:center+行内块元素

复制代码
.box{
 	width: 500px;
 	height: 300px;
 	background-color: aquamarine;
 	text-align: center;   //父级添加text-align: center;
} 
.box1{
 	width: 200px;
 	height: 100px;
 	background-color: lightpink;
 	display: inline-block;  //把div变为行内块元素
}
相关推荐
tq6J5Yg1428 分钟前
windows10本地部署openclaw
前端·python
ISkp3V8b41 小时前
从 ReAct 到 Workflow:基于云端 API 构建事件驱动的智能体
前端·react.js·前端框架
星空1 小时前
前端--A_1--THML标签
前端
GISer_Jing1 小时前
前端架构师视角:Electron 知识框架全解析(含实战+面试)
前端·面试·electron
全栈练习生1 小时前
封装数字滚动动画函数
前端
TON_G-T2 小时前
useEffect为什么会触发死循环
java·服务器·前端
Aurorar0rua2 小时前
CS50 x 2024 Notes C - 02
前端
海参崴-2 小时前
C++代码格式规范
java·前端·c++
谢尔登3 小时前
【React】setState 触发渲染的流程
前端·react.js·前端框架
摸鱼仙人~3 小时前
Vue中markdown-it基础使用教程
前端·javascript·vue.js