在平常開發中,常常會碰見居中顯示的場景,今天咱們來總結幾種。css
<div>
<p>居中顯示文字</p>
</div>
<style> div p{ text-align: center } </style>
複製代碼
<body>
<div>
<span>居中顯示文字</span>
</div>
</body>
<style> div{ text-align: center } </style>
複製代碼
<body>
<div></div>
</body>
<style> div{ width: 100px; margin: 0 auto; background-color: #f00; height: 20px; } </style>
複製代碼
div{
width: 100px;
background-color: #f00;
position: absolute;
top: 0;
left: 50%;
margin-left: -50px;
}
複製代碼
div{
width: 100px;
height: 50px;
background-color: #f00;
position: absolute;
top: 0;
right: 0;
left: 0;
margin: auto;
}
複製代碼
<body>
<div>
<span>顯示元素</span>
</div>
</body>
<style> div{ display: flex; justify-content: center; } </style>
複製代碼
div{
display: flex;
flex-direction: column;
align-items: center;
}
複製代碼
<body>
<div>
<p>顯示元素</p>
</div>
</body>
<style> div{ display: table; width: 100%; text-align: center; } </style>
複製代碼
小tips:
position:absolute; display:flex; display:block; display:table; 都會使元素變成塊元素html