设置top:0;right:0;bottom:0;left:0;的两种作用

本次记录原因

在处理如下文字效果时,在过程中使用了下面的代码语法,感到疑惑就进行了测试验证;

文字效果

代码写法

position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;

对以上代码感到疑惑,就去查找了相关内容,总结出其的两种作用:

  1. 让明确宽高的盒子水平垂直居中
  2. 让无宽高的盒子填充父容器

实验后效果图

实验效果

实验代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body, html {
            height: 100%;
        }
        .parent {
            width: 400px;
            height: 400px;
            position: relative;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #6495ed;
        }
        /*
            作用一:
            通过postion: absolute; top: 0; bottom:0; left:0; right:0;
            让明确宽高的盒子水平垂直居中
        */
        .child {
            width: 200px;
            height: 200px;
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            margin: auto;
            background-color: #b0c4de;
        }
        /*
            作用二:
            让无宽高的盒子填充父容器
        */
        .fill {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            background:linear-gradient(-45deg, #fff 0%, #fff 25%, transparent 25%, transparent 50%, 
                                        #fff 50%, #fff 75%, transparent 75%, transparent 75%);
            background-size: 10px 10px;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">
            <div class="fill"></div>
        </div>
    </div>
</body>
</html>

例子结合了两种作用对top:0;right:0;bottom:0;left:0;进行实验

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容