前端的坑【01】 margin百分比参照什么值显示?


默认状态下百分比margin如何显示?

很简单的demo,两个div

<!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>
        .outer{
            width: 300px;
            height: 300px;
            border: 1px solid blue;
        }

        .inner{
            width: 100px;
            height: 100px;
            margin-left: 50%;
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner">

        </div>
    </div>
</body>
</html>

父元素300px宽,子元素100px宽,设置子元素的margin-left:50%,此时子元素的margin-left为150px,刚好为父元素的一半(测试margin-top也是一样),也就是说 默认状态下参考的是父元素的margin

summary1

子元素的postion会影响margin的显示效果吗?

改一下子元素的position

position: absolute;

在页面宽度为800px的情况下子元素的margin变为了400px, 可以初步得出 若当前元素的postion为absolute(fixed),margin的大小会参考父级定位元素

summary2

为了验证一下结论,改一下父元素的postion

position: absolute;

此时inner的margin-left从300px变成了150px

summary

总结一下:

  1. 子元素定位方式正常(非absolute,非fixed),margin百分比参考 父元素(sticky属于正常情况)
  2. 子元素定位方式为absolute或fixed,margin百分比值参考 父级定位元素

Author: Maple
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Maple !
  TOC