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变为行内块元素
}
相关推荐
烛阴1 分钟前
武装你的Python“工具箱”:盘点10个你必须熟练掌握的核心方法
前端·python
sorryhc17 分钟前
如何设计一个架构良好的前端请求库?
前端·javascript·架构
lvchaoq42 分钟前
react 修复403页面无法在首页跳转问题
前端·javascript·react.js
郝开1 小时前
6. React useState基础使用:useState修改状态的规则;useState修改对象状态的规则
前端·javascript·react.js
Codigger官方1 小时前
Linux 基金会牵头成立 React 基金会:前端开源生态迎来里程碑式变革
linux·前端·react.js
90后的晨仔1 小时前
🌟 Vue3 + Element Plus 表格开发实战:从数据映射到 UI 优化的五大技巧
前端
ObjectX前端实验室2 小时前
【图形编辑器架构】🧠 Figma 风格智能选择工具实现原理【猜测】
前端·react.js
天桥下的卖艺者2 小时前
R语言基于shiny开发随机森林预测模型交互式 Web 应用程序(应用程序)
前端·随机森林·r语言·shiny
技术钱2 小时前
vue3 两份json数据对比不同的页面给于颜色标识
前端·vue.js·json
路很长OoO2 小时前
Flutter 插件开发实战:桥接原生 SDK
前端·flutter·harmonyos