CSS布局(一) —— 居中布局

//html结构
<div cless="wrap">
	<div class="content"></div>
</div>

1 居中布局

1.1 水平居中布局

方案一: 定位 + transform

解释:定位使子级元素左上角坐标位于父级元素水平方向中心,设置transform使子级元素向左移动自身宽度的一半,从而使元素居中。
注意:transform是CSS3的内容,存在浏览器兼容问题。

.wrap {
	width: 500px;
	height: 500px;
	background-color: red;
	position: relative;
}
.content {
	width: 200px;
	height: 200px;
	background: blue;
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
}

方案二: display:inline-block + text-align:center

解释:display:inline-block使子级元素拥有行内标签的文本属性,text-align:center使元素左右居中。

.wrap {
	width: 500px;
	height: 500px;
	background-color: red;
	text-align: center;
}
.content {
	width: 200px;
	height: 200px;
	background: blue;
	display: inline-block;
}

方案三: display:block + margin:0 auto

解释:display:block使子级变成块级元素(使用display:table也行),可以使用margin自动分配居中。
注意:如果子元素脱离文档流,会导致margin无效。

.wrap {
	width: 500px;
	height: 500px;
}
.content {
	width: 200px;
	height: 200px;
	background: blue;
	display: block;
	margin: 0 auto;
}

1.2 垂直居中布局

方案一: 定位 + transform

解释:定位使子级元素左上角坐标位于父级元素竖直方向中心,设置transform使子级元素向上移动自身高度的一半,从而使元素居中。

.wrap {
	width: 500px;
	height: 500px;
	background-color: red;
	position: relative;
}
.content {
	width: 200px;
	height: 200px;
	background: blue;
	position: absolute;
	top: 50%;
	transform: translateY(-50%);
}

方案二:display:table-cell + vertical-align: middle

解释:display:table-cell是元素具有td元素的行为,它的子元素布局类似文本元素,可以再父元素中使用vertical-align: middle进行垂直居中。


.wrap {
	width: 500px;
	height: 500px;
	background-color: red;
	display: table-cell;
	vertical-alilgn: middle;
}
.content {
	width: 200px;
	height: 200px;
	background: blue;
}

水平垂直居中布局

方案一: 定位 + transform

.wrap {
	width: 500px;
	height: 500px;
	background-color: red;
	position: relative;
}
.content {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 200px;
	height: 200px;
	background: blue;
}

方案二: 水平布局方案三 + 垂直布局方案二

解释:(略,请看上文)

.wrap {
	width: 500px;
	height: 500px;		
	background-color: red;
	display: table-cell;
	vertical-alilgn: middle;
}
.content {
	width: 200px;
	height: 200px;
	background: blue;
	margin: 0 auto;
}

flex居中布局

注意:flex是CSS3提出的,不兼容IE8以下浏览器版本。需要考虑浏览器兼容性
解释:justify-content: center:主轴方向水平居中;align-items: center:垂直居中。

.wrap {
	width: 500px;
	height: 500px;
	background-color: red;
	display: flex;
	justify-content: center;
	align-items: center;
}
.content {
	width: 200px;
	height: 200px;
	background: blue;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值