CSS 中几种常见的垂直居中的方法

在开发和面试中经常会遇到垂直居中的问题,下面总结了几种常见的实现方法:
几种方法公用的 HTML:

<div class="root">
    <div class="item">
    </div>
</div>
  1. 通过 display: flex; 实现

    .root {
    	width: 500px;
    	height: 500px;
    	border: 2px solid black;
    	display: flex;
    	justify-content: center;
    	align-items: center;
    }
    .item {
    	width: 200px;
    	height: 200px;
    	background-color: brown;
    }
    

    对弹性布局不了解的小伙伴可以参考另一篇文章:Flex 布局(弹性盒子、弹性布局)

  2. 通过 display: table-cell; 实现

    .root {
    	width: 500px;
    	height: 500px;
    	border: 2px solid black;
    	display: table-cell;
    	text-align: center;
    	vertical-align: middle;
    }
    .item {
    	width: 200px;
    	height: 200px;
    	background-color: brown;
    	display: inline-block;
    }
    
  3. 通过 margin + transform实现

    .root {
    	width: 500px;
    	height: 500px;
    	border: 2px solid black;
    	/*防止外边距塌陷,解决办法:父元素加上边框或overflow: hidden;*/
    }
    .item {
    	width: 200px;
    	height: 200px;
    	background-color: brown;
    	margin: 50% auto;
    	transform: translateY(-50%);
    }
    
  4. 通过 inline-block + vertical-align实现

    .root {
    	width: 500px;
    	height: 500px;
    	border: 2px solid black;
    	line-height: 500px;
    	text-align: center;
    }
    .item {
    	width: 200px;
    	height: 200px;
    	background-color: brown;
    	display: inline-block;
    	vertical-align: middle;
    }
    
  5. 通过 absolute + 负margin实现

    .root {
    	width: 500px;
    	height: 500px;
    	border: 2px solid black;
    	position: relative;
    }
    .item {
    	width: 200px;
    	height: 200px;
    	background-color: brown;
    	position: absolute;
    	left: 50%;
    	top: 50%;
    	margin-top: -100px;
    	margin-left: -100px;
    }
    
  6. 通过 absolute + margin: auto;实现

    .root {
    	width: 500px;
    	height: 500px;
    	border: 2px solid black;
    	position: relative;
    }
    .item {
    	width: 200px;
    	height: 200px;
    	background-color: brown;
    	position: absolute;
    	left: 0;
    	top: 0;
    	bottom: 0;
    	right: 0;
    	margin: auto;
    }
    
  7. 通过 absolute + transform实现

    .root {
    	width: 500px;
    	height: 500px;
    	border: 2px solid black;
    	position: relative;
    }
    .item {
    	width: 200px;
    	height: 200px;
    	background-color: brown;
    	position: absolute;
    	left: 50%;
    	top: 50%;
    	transform: translate(-50%, -50%);
    }
    

原文链接:8种垂直居中的方法

posted @ 2022-02-28 19:14  太轻描淡写了  阅读(1457)  评论(0编辑  收藏  举报