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種垂直居中的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM