css 上下左右居中的几种方法

2023-11-05

html结构

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

1.父元素宽高固定,子元素宽高固定。那么子元素可以通过上、左右的固定margin-left: (父元素宽度 - 子元素宽度)/2、margin-top: (父元素高度 - 子元素高度)/2值实现居中

.father{
	width: 600px;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0
}
.son{
	width: 100px;
	height: 100px;
	background-color: blue;
	margin-left: 250px;
	margin-top: 150px;
}

2.父元素宽度是不固定的高度固定,此时子元素可以 margin-left:automargin-right:auto

既我们熟悉的 margin: 0 auto

.father{
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	width: 100px;
	height: 100px;
	background-color: blue;
	margin: 150px auto 0 auto;
}

3.父元素宽高不固定(涉及元素高度百分比问题,如果元素高度设置为百分数,那么此元素的父元素必须固定高度),此处父元素以vh为例子,子元素利用 calc 函数计算获取居中margin-top值(注意calc函数的写法,括号内的计算符号两边必须有空格

.father{
	height: 100vh;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	width: 100px;
	height: 100px;
	background-color: blue;
	margin-left: auto;
	margin-right: auto;
	margin-top: calc(50vh - 50px);
}

4.父元素position: relative;宽高无所谓。子元素position: absolute;利用margin-left:-50px (负的居中元素宽度的一半,如margin-top:-50px(负的居中元素高度的一半,此处例子子元素的宽高均为100px实用时注意具体计算);矫正

.father{
	position: relative;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
	box-sizing: border-box;
}
.son{
	position: absolute;
	background-color: blue;
	width: 100px;
	height: 100px;
	left: 50%;
	top: 50%;
	margin-left: -50px;
	margin-top: -50px;
}

5.还是position定位,子元素利用css3 transform: translate(-50%,-50%);偏移实现位置矫正

.father{
	position: relative;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
	box-sizing: border-box;
}
.son{
	position: absolute;
	background-color: blue;
	width: 100px;
	height: 100px;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
}

6.还是position,父元素大小无所谓。子元素上下左右位置均设置为0,margin:auto

.father{
	position: relative;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	position: absolute;
	background-color: blue;
	width: 100px;
	height: 100px;
	margin: auto;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
}

7.flex,父元素大小无所谓,子元素大小无所谓

.father{
	display: flex;
	justify-content: center;
	align-items: center;
	height: 400px;
	border: 1px solid #000;
	background-color: #f0f0f0;
	box-sizing: border-box;
}
.son{
	background-color: blue;
	width: 100px;
	height: 100px;
}

8. 利用子元素display: inline-block;行内块级元素特性。

父元素高度固定且行高等于自身高度;

.father{
	height: 400px;
	line-height: 400px;
	text-align: center;
	font-size: 0;
	border: 1px solid #000;
	background-color: #f0f0f0;
}
.son{
	display: inline-block;
	background-color: blue;
	width: 100px;
	height: 100px;
	vertical-align: middle;
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

css 上下左右居中的几种方法 的相关文章

随机推荐