纯CSS设置元素垂直水平居中的几种方法

分为定位的方法,和不定位的方法。

使用定位的方法:
  1. 定位+transform:
    父元素相对定位,子元素绝对定位,设置子元素的 top:50%; left:50%;transform:translate: (-50%,-50%),代码对应类名f1,box1。
  2. 定位+margin:
    父元素相对定位,子元素绝对定位,设置子元素的 top:50%; left:50%;margin-left:负的自身宽度的一半,margin-top:负的自身高度的一半。代码对应类名f1,box1。代码都写在了这一部分里,有标注。
  3. 定位+margin:
    父元素相对定位,子元素绝对定位。设置子元素的left,right,bottom,top都为0,margin:auto;代码对应类名f3,box3。
不用定位的方法:
  1. table-cell方法,赋予父元素单元格的属性:
    父元素display:table-cell; vertical-align: middle;设置子元素的margin:0 auto;代码对应类名 f2,box2。
  2. flex弹性盒子布局:
    设置父元素display: flex;
    justify-content: center;
    align-items: center;
    代码对应类名 f4,box4。
html代码:

外层div与内层div,span标签区分第几种,序号。

<body>
	<span>1</span>
	<div class="f1">
		<div class="box1"></div>
	</div>
	<span>2</span>
	<div class="f2">
		<div class="box2"></div>
	</div>
	<span>3</span>
	<div class="f3">
		<div class="box3"></div>
	</div>
	<span>4</span>
	<div class="f4">
		<div class="box4"></div>
	</div>
</body>
style内容:
.f1 {
			width: 300px;
			height: 200px;
			border: 1px solid red;
			position: relative;
		}

		.box1 {
			position: absolute;
			width: 100px;
			height: 50px;
			background-color: pink;
			/*父元素相对定位,
			子元素绝对定位,
			设置子元素的 top:50%; left:50%;
			transform:translate: (-50%,-50%)
			*/
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			/* 方法2:父元素相对定位,子元素绝对定位
			设置子元素:
			top:50%; 
			left:50%;
			margin-left: 负的宽度一半 
			margin-top: 负的高度一半。
			这两种类似,我写在了一个类里面。
			 */			
			/* margin-left: -50px;
			margin-top: -25px; */
		}


		.f2 {
			width: 300px;
			height: 200px;
			background: rgb(241, 241, 43);
			border: 1px solid #555555;
			/* 方法3:父元素display:table-cell;vertical-align:middle;
			子元素:margin:0 auto;*/
			display: table-cell; /*转换为table单元格显示*/
			/*垂直居中*/
			vertical-align: middle;			
		}

		.box2 {
			width: 100px;
			height: 100px;
			background: pink;
			margin: 0 auto;
			/*水平居中*/
		}

		.f3 {
			width: 300px;
			height: 200px;
			border: 1px solid red;
			background: lightyellow;
			/* 方法4:
			父元素相对定位,子元素绝对定位,
			设置子元素left,right,bottom,top都为0,margin:auto;*/
			position: relative;
		}

		.box3 {
			position: absolute;
			width: 100px;
			height: 100px;
			background: pink;

			left: 0;
			top: 0;
			bottom: 0;
			right: 0;
			margin: auto;
		}

		.f4 {
			width: 300px;
			height: 200px;
			border: 1px solid red;
			background: lightyellow;
			/*方法5:flex弹性盒子布局
			设置父元素display: flex;
			justify-content: center;
			align-items: center;*/
			display: flex;
			/*主轴方向居中,即水平居中*/
			justify-content: center;	
			/*侧轴方向居中,即水平居中*/		
			align-items: center;
		}

		.box4 {
			width: 100px;
			height: 100px;
			background: pink;
		}

效果截图
文章整理完了,欢迎测试代码或下方评论哦~

发布了30 篇原创文章 · 获赞 26 · 访问量 7205

猜你喜欢

转载自blog.csdn.net/aaqingying/article/details/88943918