水平垂直居中方法

 有两种常用办法:

  1. 绝对定位+margin边距(传统方法)
  2. 绝对定位+translate位移
  3. flex布局

 

  • 绝对定位方法
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="">
        <p></p>
    </div>
</body>

</html>
<style>
    div {
        width: 300px;
        height: 300px;
        background: #33d;
        position: relative;
    }

    p {
        position: absolute;
        width: 100px;
        height: 100px;
        background: green;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        /* margin-left: -50px;
        margin-top: -50px; */

    }
</style>

 

  • flex布局水平垂直居中方法
    div {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 300px;
        height: 300px;
        background: #33d;
    }

    p {
        width: 100px;
        height: 100px;
        background: pink;

    }

 

posted on 2023-07-25 21:17  码农-编程小子  阅读(3)  评论(0编辑  收藏  举报