CSS样式:垂直居中 水平居中 的几种方法

1、flex

使用flex布局,让居中元素的父元素为flex属性,让它在水平的主轴(main axis)和垂直的交叉轴(cross axis)居中就好
html:

<div class="father">
	<div class="son"></div>
</div>

css:

*{
	margin:0;
	padding:0;
}
.father{
	width:500px;
	height:500px;
	background-color:bule;
	display:flex;//父元素设置flex属性
	justify-content:center;//水平居中
	align-items:center;//垂直居中
}
.son{
	width:100px;
	height:100px;
	background-color:red;
}

flex水平居中:justify-content:center
flex垂直居中:align-items:center

2、使用绝对定位实现

父元素相对定位,子元素绝对定位
html同上
css:

.father{
	width:500px;
	height:500px;
	background-color:bule;
	position:relative;
}
.son{
	width:100px;
	height:100px;
	background-color:red;
	positon:absolute;
	top:0;
	bottom:0;
	left:0;
	right:0;
	margin:auto;
}

为子元素top: 0; left: 0; bottom: 0; right: 0;将给浏览器重新分配一个边界框,此时该块块将填充其父元素的所有可用空间,所以margin 垂直水平方向上有了可分配的空间。再设置margin 垂直方向上下为auto,即可实现垂直水平居中。(注意宽度高度得设置)。

如果已知高度和宽度(高度必须设置,宽度可跟随父级一致)
则css:

p{
	width:100px;
	height:100px;
	background:red;
	position:absolute;
	top:50%;
	left:50%;
	margin-left:-50px;
	margin-top:-50px;
	}

3、position+transform实现

html:同上
css:

.father {
  background:bule;
  height:500px;
  position: relative;
}

.son{
  position: absolute;
  left:50%;
  top:50%;//50%并不是居中的,因为它是以元素的上border为标准移动50%的
  transform:translate(-50%,-50%)//所以我们需要像上移动元素自身高度一半儿的距离,前-50%表示垂直,后——50%表示居中
}

4、对单行文本的行内元素

line-height控制垂直居中,text-align控制行内水平居中
html:

<div>
	<span>我是行内</span>
</div>

css:

div{
	width:300px;
	height:100px;
	background:pink;
	text-align:center;
	line-height:100px;//设置的和行高一样
	}
span{
	background:blue;
	}

如果是多行文本,则水平不变,垂直用display:table-cell;vertical-align:middle
css:

div{
	width:300px;
	height:100px;
	background:pink;
	text-align:center;
	display:table-cell;
	vertical-align:middle;
	}
span{
	background:blue;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值