clientWidth、scrollWidth与offsetWidth的区别详解

本文详细解析了CSS中clientWidth、scrollWidth与offsetWidth的区别及应用场景。通过实例对比了不同情况下的测量结果,包括存在滚动条时元素尺寸的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

clientWidth、scrollWidth与offsetWidth这三种经常会混淆,举例解释这三种宽度

1、没有滚动条的情况

 #boxWrap {
        width: 300px;
        height: 300px;
        background: pink;
        overflow: auto;
    }

    #box1 {
        width: 200px;
        height: 200px;
        background: gray;
        margin: 0 auto;
        padding: 10px;
        border: 5px solid #ccc;
        box-sizing: content-box;
    }
<div id="boxWrap">
    <div id="box1">this is the box </div>
    </div>
<script type="text/javascript">
var clientWidth=document.getElementById("box1").clientWidth;//220     clientWidth=content+padding
var scrollWidth=document.getElementById("box1").scrollWidth;//220     scrollWidth=content+padding
var offsetWidth=document.getElementById("box1").offsetWidth;//230     offsetWidth=content+padding+border
alert(clientWidth + " , " + scrollWidth + " , " + offsetWidth)
</script>

上面没有滚动条的情况下clientWidth:220   scrollWidth:220    offsetWidth:230

2、含有滚动条的情况

(1)对于里面的box(box2)

#boxWrap {
        width: 300px;
        padding:10px;
        border:1px solid #ccc;
        height: 300px;
        background: pink;
        overflow: auto;
        box-sizing: content-box;
    }

   
    #box2 {
        width: 400px;
        height: 400px;
        background: gray;
        margin: 0 auto;
        padding: 10px;
        border: 5px solid #ccc;
        box-sizing: content-box;
    }

<div id="boxWrap">
      <div id="box2">this is another box </div>
</div>
<script type="text/javascript">
var clientWidth2 = document.getElementById("box2").clientWidth; //420     
var scrollWidth2 = document.getElementById("box2").scrollWidth; //420     
var offsetWidth2 = document.getElementById("box2").offsetWidth; //430     
alert(clientWidth2 + " , " + scrollWidth2 + " , " + offsetWidth2) 
</script>

在有滚动条时对于里面的box来说是跟没有滚动条是一样的

(2)对于外面的box(boxWrap)

<script type="text/javascript">
var clientWidth3 = document.getElementById("boxWrap").clientWidth; //303  
var scrollWidth3 = document.getElementById("boxWrap").scrollWidth; //440     
var offsetWidth3 = document.getElementById("boxWrap").offsetWidth; //322     
alert(clientWidth3 + " , " + scrollWidth3 + " , " + offsetWidth3)
</script>

外面的box受到里面box的影响,如果里面的box比较大,会有滚动条,

外面box的clientWidth= content+padding-滚动条的宽度(大概是17px)

外面box的scrollWidth=里面box的总宽度(里面box的content+padding+border)+外面box一边的padding

外面box的offsetWidth=外面box自身的content+padding+border

转载于:https://my.oschina.net/u/2612473/blog/1809682

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值