解决“有边框的子元素宽度设定绝对值后,缩放浏览器会错位”的两种方法

现象:

用浮动布局时, 如果为子元素的宽度指定绝对值,并且子元素具有边框,在缩放浏览器的时候会出现错位现象。
这种现象产生的原因是:
浏览器缩放时,子元素父元素的内容都等比例缩放,而子元素的边框不能等比例缩放,在缩放到达一定程度后,会造成子元素大于父元素,从而产生错位现象。

举例:

<style>

    .wrapper {
        width: 400px;
        background-color: pink;
    }
    .wrapper::after {
        content: '';
        display: block;
        clear: both;
    }
    .wrapper > div {
        float: left;
        height: 200px;
    /*    box-sizing: border-box;*/
    }
    .wrapper > div.left {
        width: 99px;
        border-right: 1px solid #ccc;
        background-color: orange;
    }
    .wrapper > div.right {
        width: 300px;
        background-color: lightblue;
    }
</style>

<div class="wrapper">

    <div class="left">left</div>
    <div class="right">right</div>
</div>

正常显示效果:图片描述

缩小为原本67%后产生错位:图片描述

解决方法一:

利用box-sizing属性的border-box.[border-box:指定宽度和高度(最小/最大属性)确定元素边框box。也就是说,对元素指定宽度和高度包括padding和border的指定。内容的宽度和高度减去各自双方该边框和填充的宽度从指定的"宽度"和"高度"属性计算]
css:
<style>

    .wrapper {
        width: 400px;
        background-color: pink;
    }
    .wrapper::after {
        content: '';
        display: block;
        clear: both;
    }
    .wrapper > div {
        float: left;
        height: 200px;
        /*解决错位*/
        box-sizing: border-box;
    }
    .wrapper > div.left {
        width: 99px;
        border-right: 1px solid #ccc;
        background-color: orange;
    }
    .wrapper > div.right {
        width: 300px;
        background-color: lightblue;
    }
</style>

缩放50%后的效果没有错位

解决方法二:

将子元素浮动,即两个元素不在一个文档流中,从而避免产生错位
CSS:
<style>

    .wrapper {
        width: 400px;
        background-color: pink;
    }
    .wrapper > div {
        height: 200px;
    }
    .wrapper > div.left {
        width: 99px;
        border-right: 1px solid #ccc;
        background-color: orange;
        float: left;
    }
    .wrapper > div.right {
        margin-left: 100px;
        width: 300px;
        background-color: lightblue;
    }
</style>

缩放30%后的效果:图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值