Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the CSS specification say is correct way to measure an elements width?

Chrome seems to measure an elements width from the inside of the margin including padding but Firefox and IE measure the boxes width where the border is (not including padding but inside margin). measuring the elements width from the border makes sense to me and is also helpful when coding because turning on borders will let you see the width of the element very easily but my question is what the CSS specification says is the correct way to measure the width of an element and if chrome is wrong or IE and Firefox are

thanks for your help

like image 650
Carter Cole Avatar asked Feb 28 '23 18:02

Carter Cole


2 Answers

The W3C CSS 2.1 Box Model Specification says that the width of an element does not include margin, border or padding.

In fact by specifying the CSS width or height properties you specify the space available to the content of a box (that is called content area in the specification) which does not include padding, margin or border.

Look at this example:

div { width: 100px; padding: 10px; margin: 20px; border: 2px; }

The distance between the vertical borders (including them) is width + padding-left + padding-right + border-right-width + border-left-width. Margins are outside of the border-box. The width (as intended by the CSS specifications) is instead 100px.

Internet Explorer renders web pages in Standard Mode or in Quirks mode. If you want IE to behave as it should (so following CSS Standards) you have to force it to use the Standard Mode by using one of the DOCTYPEs reported in this article: http://www.alistapart.com/articles/doctype/

This technique is called doctype-switch.

Firefox and the majority of other browsers follows the standard box model.

You can read the W3C box model specification here: http://www.w3.org/TR/CSS21/box.html#box-dimensions But I suggest you to read a more easy-to-read (but really good) article like this: http://reference.sitepoint.com/css/boxmodel

Another thing to say is that the CSS 3 specifications will include the box-sizing property which will allow to specify for every element the way to interpret the width property (so if excluding or including padding and borders). Anyway it will take years for the majority of browsers to implement the new (and not yet finished) CSS 3 specifications.

like image 174
Andrea Zilio Avatar answered Mar 02 '23 06:03

Andrea Zilio


Feel free to read it. Of course, every browser in the last decade implemented it differently.

The width property of an element is supposed to be the "content area width", and is not supposed to include margins, padding, or borders. IE did not implement it this way in certain versions and situations. Generally other browsers follow the spec.

like image 22
zombat Avatar answered Mar 02 '23 07:03

zombat