margin-top参考点与百分数计算

版权声明:本文为博主原创文章,若文章中有错误请联系博主改正,请不要恶意留言(不喜欢请绕道)。欢迎大家转载,转载时请注明原文地址:https://blog.csdn.net/qq_37674616/article/details/81568944

下面是追溯过程:

1.关于外边框基准问题(参照点)    

   下面我们来分析几个案例:

            案例的代码 大致如下: 

<style>

        *{

            margin:0;

        }

        .box{

            width: 1000px;

            height: 500px;

            background-color: teal;

        }



        .left{

            width:100px;

            height: 100px;

            margin-top: 10px;

            background-color: orange;

        }

    </style>



<body>

    <div class="box" >

        <div class="left" >

        </div>

    </div>

</body>

案例一

如果此时给.left加入 margin-top:50%; 

        * 关于margin-top中 % 是以父元素的宽度为基准进行计算

    有人就会问,不对啊,我给子元素加的 margin-top 为什么父元素也下移呢?

                那先看下面这个案例:

案例二

 案例三 如果我给 .box div中加入文字呢?

    

案例四

    

   

    我们从案例一和案例二中看到,margin-top的参考点都是视口上方。案例三中我们发现,margin-top的参考点是相对文字底部,这也就是案例三中橙色上面有一片空白的地方原因。

        结论:如果父元素中有内容的时候,子元素的外边距是相对父元素内容,如果没有内容则一直向上追溯寻找如果都没有找到(案例四中可以看到),最终以浏览器视口为参考点。

或者创建一个[BFC](https://blog.csdn.net/qq_37674616/article/details/90606744)

    那么大家来看这个案例:

        以上内容仅个人观点,如有不对请留言指正,谢谢!

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
margin-top用于设置其所作用的标签的上外距离,但是该上外边距相对于谁呢?根据引用\[1\]中的解释,对于margin-top来说,它的参照物不是父div,而是body。这是因为如果父div没有边界,margin-top就无法参照。所以,margin-top实际上是相对于body来设置的。这也解释了为什么在某些情况下,我们设置了margin-top,但效果并不如预期。 #### 引用[.reference_title] - *1* [重新认识margin-top和margin-bottom](https://blog.csdn.net/wangshuxuncom/article/details/53214104)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [详述外边距样式属性(margin-top margin-right margin-bottom margin-left margin)](https://blog.csdn.net/IT_Helianthus/article/details/90356824)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [CSS中的四种定位以及top和margin-top的区别](https://blog.csdn.net/qq_40935723/article/details/100182374)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值