Pjhdfsd
Pjhdfsd

Reputation: 11

Difference between document.body.clientWidth and document.documentElement.clientWidth

I am trying to understand the difference bewteen the following two javscript syntax-

document.body.clientWidth
document.documentElement.clientWidth

Both the values are match everytime on my device and on all the browsers. But, for one of my friend, the values don't match on chrome. He is using Windows Surface laptop. When he uses microsoft edge, the values match. We have a logic to show CSS disable model in case the values dont match. Can anyone guide me on the difference between the two syntaxes and why is it coming different

Upvotes: 1

Views: 1347

Answers (1)

A Haworth
A Haworth

Reputation: 36512

The difference is that

document.body.clientWidth will give the width of the body element

while

document.documentElement.clientWidth will give the width of the document's element, which is the html element.

In standard mode (i.e. with doctype defined) I got a different width for the body and the html elements. The difference was 16px which is 2*8px, 8px being the default left and right margin widths added by the browser.

In quirks mode (i.e. with doctype not defined) it gave both widths the same (i.e. no 8px default margin).

These results were all as expected. (Tested on Edge/Chrome and Firefox on Windows 10).

Here's the code which gave the different widths:

<!doctype html>
<html>
<head>
</head>
<body>
<script>
alert(document.body.clientWidth);// on my laptop got 1520 as expected (screen/viewport width less 2*8px default margin)
alert(document.documentElement.clientWidth);// on my laptop got 1536 as expected (screen/viewport width)
</script>
</body>
</html>

And to try it in quirks mode simply remove the first line.

To get the differences that you have mentioned means there is something else going on. There must be some more styling, perhaps an added border or removed margin setting or...

There is a lot of info out there about the difference between quirks mode and standard mode e.g. https://en.wikipedia.org/wiki/Quirks_mode but it seems more likely that there is some CSS styling or some content in the body of the examples you are citing which causes the differences you are seeing.

Upvotes: 1

Related Questions