CSS - Width property (of a box)

Boxdim

About

The width property specifies the width of boxes and it's calculation is defined by the box sizing property.

Width HTML vs CSS attribute

Don't be confuse ! This is not the same attribute than the HTML width attribute that is only limited to an handful of HTML element that already have an intrinsic width such as img, iframe, …

If you want to set a width on a p element for instance,

  • you need to use the css width attribute
<p style="width:80px;border:1px solid aqua;">
This paragraph will be constraint by the CSS width.
</p>
<p width="80px" style="border:1px solid aqua;">
This paragraph will not follow the width HTML attribute
</p>

Formula

The following property have an effect on the width calculation:

  • The box sizing property defines the calculation.
  • The min-width and max-width properties override width.
  • The white space property may prevents a line box to (wrap|break)
  • The type of block: An inline block will not take the width into account.

Formula taking into account only the box sizing property:

<MATH> \text{Width Size} = \text{Content Size} </MATH>

<MATH> \text{Width Size} = \text{Content Size} + \text{Padding Size} + \text{Border Size} </MATH>

Usage

Values 	<length> | <percentage> | auto | inherit | min-content | max-content
Initial value 	auto
Applies to 	All elements but non-replaced inline elements, table rows, and row groups
Inherited 	No 

where:

Example

Box Sizing

See CSS - Box sizing (property and definition)

Inline vs Block Box

.coloredBox {
	width: 20px; 
	height: 20px; 
	border-left: 4px solid aqua;
	border-right: 4px solid red;
	border-bottom: 4px solid black;
	border-top: 4px solid blue;
        display:block;
}
  • The type of block is important. It must be block box
<p>A block box</p>
<span class="coloredBox"></span>

<p>A inline box will not respond to the width</p>
<span class="coloredBox" style="display:inline"></span>

The p element renders by default as a block box whereas the span element renders default as a inline box

DOM Get

<div id="box">
Box
</div>
#box {
    height:25px;
    width:50px;
    padding:4px;
    border: 2px solid #FFF;
    background-color:#D5D8CB;
}
let element = document.getElementById("box") ;
console.log("Box-Sizing defines the width as been the width of the "+window.getComputedStyle(element).boxSizing);
console.log("Client Width: "+element.clientWidth+" (50+2x4)");
console.log("Offset Width: "+element.offsetWidth+" (50+2x4+2x2)");
console.log("Scroll Width: "+element.scrollWidth+" (client width)");

where:

  • clientWidth includes:
    • the width
    • and horizontal padding.
  • offsetWidth includes:
    • the width,
    • horizontal padding,
    • and vertical borders.
  • scrollWidth == clientWidth

Documentation / Reference

Task Runner