zl程序教程

您现在的位置是:首页 >  前端

当前栏目

CSS中的那些百分比

CSS 那些 百分比
2023-09-11 14:19:18 时间

宽高

  • 如果widthheight的值为百分比,那么他的值的参照为父元素的宽高
<div style="width: 200px;height: 100px; border: 1px solid black;">
    <div style="width: 50%; height: 50%; background-color: red;"></div>
</div>

我们看到的图形如在这里插入图片描述

margin和padding

  • 一般是按照父元素的宽度来进行计算的
<div style="width: 200px;height:100px;border:1px solid black">
    <div style="margin-top: 50%; border: 1px solid red;">子元素1</div>
    <div style="padding-left: 50%;border: 1px solid rgb(54, 103, 196);">子元素2</div>
</div>

我们看到的图形如在这里插入图片描述
我们就会发现百分比所参照的就是父元素的宽度

定位

相对定位

  1. topbottom是相对于父元素的高
  2. leftright是相对于父元素的宽
<body>
    <div style="width: 200px;height: 100px; border: 1px solid black;">
        <div style="
        width: 50px; height: 50px; background-color: red;
        position: relative;
        top: 50%;
        left: 50%;
        "></div>
    </div>
</body>

我们可以看到如下图片在这里插入图片描述

绝对定位

  1. 先找到有没有定位的元素
  2. 如果向上找到了定位元素,以定位元素的宽高为参照
  3. 如果向上没有找到定位元素,就以html标签为参照
<body>
    <div style="
    width: 200px;height: 100px; 
    border: 1px solid black;
    position: relative;
    ">
        <div style="
        width: 50px; height: 50px; background-color: red;
        position: absolute;
        top: 50%;
        left: 50%;
        "></div>
    </div>
</body>

如下图形在这里插入图片描述

translate

  • 在translate中使用的百分比,他是根据元素自身的大小来进行计算的
<html lang="en">
<head>
    <title>Document</title>
    <style>
        body{
            margin: 0;
            padding: 0;
        }
        #box{
            width: 100px;
            height: 100px;
            background-color: red;
            position: relative;
            transform: translateX(50%);
        }
    </style>
</head>
<body>
    <div id="box"></div>
</body>
</html>

在这里插入图片描述

  1. 通过图像我们可以看出来盒子的宽度为100px,但是他向右移动了50px