在平常开发中,常常会碰见居中显示的场景,今天咱们来总结几种。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