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变为行内块元素
}
相关推荐
Zestia9 分钟前
页面点击跳转源代码?——element-jumper插件实现
前端·javascript
前端小白19959 分钟前
面试取经:工程化篇-webpack性能优化之优化loader性能
前端·面试·前端工程化
PineappleCoder9 分钟前
大小写 + 标点全搞定!JS 如何精准统计单词频率?
前端·javascript·算法
zhangbao90s11 分钟前
Web组件:使用Shadow DOM
前端
hhy前端之旅11 分钟前
语义版本控制:掌握版本管理的艺术
前端
coding随想11 分钟前
深入浅出DOM操作的隐藏利器:Range(范围)对象——掌控文档的“手术刀”
前端
前端小白199512 分钟前
面试取经:工程化篇-webpack性能优化之减少模块解析
前端·面试·前端工程化
一枚前端小能手12 分钟前
🏗️ 项目越来越大维护不动了,微前端架构了解一下
前端
文艺理科生21 分钟前
Nuxt.js入门指南-Vue生态下的高效渲染技术
前端·vue.js·nuxt.js
夏小花花25 分钟前
vue3 ref和reactive的区别和使用场景
前端·javascript·vue.js·typescript