css 单个对象居中
2021-07-03 本文已影响0人
devmao
<!--第一种方式: text-align 配合 line-height -->
<div style="width: 100px; height: 100px;background-color: red; text-align: center;">
<p style="line-height: 100px;">中心</p >
</div>
<!--第二种方式: flex -->
<div style="width: 100px; height: 100px;background-color: green; display: flex; align-items: center; justify-content: center;margin-top: 30px">
<p>中心</p >
</div>
<!--第三种方式: 相对定位 先偏50% 再反偏自身50% -->
<div style="width: 100px; height: 100px;background-color: blue; margin-top: 30px;">
<p style="transform: translateY(-50%); position: relative; top: 50%; text-align: center">中心</p >
</div>
<!--第四种方式: 原理同上 -->
<div style="width: 100px; height: 100px;background-color: purple; margin-top: 30px;position: relative">
<p style="transform:translate(-50%,-50%); position: absolute; margin-top: 50%; margin-left: 50%;">中心</p >
</div>