爱达的日志
三种方法让一个盒子在父盒子中垂直水平居中
三种方法让一个盒子在父盒子中垂直水平居中

1. 把父元素转换成表格用vertical:middle垂直居中,子元素转换成行内块用text-aligin:center居中

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .father {
            height: 500px;
            width: 500px;
            background-color: hotpink;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            margin: 0 auto;
        }

        .son {
            display: inline-block;
            vertical-align: middle;
            height: 300px;
            width: 80px;
            background-color: pink;
        }
    </style>
</head>

<div class="father">
    <div class="son"></div>
</div>


</html>

2. 用C3的transform实现居中 (定位之后走一半的左和上,然后再用transform去走自身的一半)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .father {
            height: 500px;
            width: 500px;
            background-color: hotpink;
            position: relative;
        }

        .son {
            height: 100px;
            width: 100px;
            background-color: yellow;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%)
        }
    </style>
</head>

<div class="father">
    <div class="son"></div>
</div>
</html>

3. 利用flex布局(最简单的方式)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .father {
            height: 500px;
            width: 500px;
            background-color: hotpink;
            display: flex;
            justify-content: center;
            align-items: center;

        }

        .son {
            height: 100px;
            width: 100px;
            background-color: yellow;

        }
    </style>
</head>

<div class="father">
    <div class="son"></div>
</div>


</html>

首页      研究      三种方法让一个盒子在父盒子中垂直水平居中

发表评论

textsms
account_circle
email

爱达的日志

三种方法让一个盒子在父盒子中垂直水平居中
[db:摘要]
扫描二维码继续阅读
2019-08-30