【CSS】垂直水平居中

1.水平居中

text-align:center

对文字、图片等行内元素居中的方式

<body>
  <div style="text-align: center;">
    <img src="./hashiqi1.jpg">
    <p>来点文字</p>
    <button>我是按钮</button>
  </div>
</body>

flex

<div style="display: flex;flex-direction: column">
    <img style="align-self: center" src="./hashiqi1.jpg">
</div>

下面这个方法对只有一个元素有效

<div style="display: flex;justify-content: center;align-items: center">
    <img style="align-self: center" src="./hashiqi1.jpg">
</div>

flex布局非常好用,唯一就是兼容性问题

margin:auto
对于块级元素有效

<div style="display: flex;flex-direction: column;text-align: center">
    <p style="margin: auto">来点文字</p>
</div>

2.垂直居中

table和table-cell

 <div style="display: table;width: 500px;height: 200px;border: 1px solid red;">
    <p style="display: table-cell;vertical-align: middle;">来点文字</p>
 </div>

positon

<div style="position:relative; width: 500px;height: 200px;border: 1px solid red;">
        <div style="position: absolute;top:50%;transform:translate(-50%,-50%);width: 100px;height: 100px;text-align:center;">块级元素</div>
</div>

3.水平垂直居中

position

<div style="position:relative; width: 500px;height: 200px;border: 1px solid red;">
    <div style="position: absolute;top:50%;left:50%;transform:translate(-50%,-50%);width: 100px;height: 100px;border: 1px solid gold;text-align:center;line-height:100px">块级元素</div>
</div>

flex

<div style="display:flex;justify-content: center; align-items:center; width: 500px;height: 200px;border: 1px solid green;text-align:center;line-height:100px ">
    <div style="width: 100px;height: 100px;border: 1px solid gold">块级元素</div>
</div>

适用于块级元素

扫描二维码关注公众号,回复: 5530701 查看本文章

猜你喜欢

转载自blog.csdn.net/jzq950522/article/details/88346719