CSS - Length Value (Size)

Boxdim

CSS - Length Value (Size)

Introduction

Lengths refer to horizontal or vertical measurements.

Format

The format of a length value is a number (with or without a decimal point) immediately followed by a unit identifier

number unit

where:

In sizing attribute such as width and height, there is a default unit and this is the pixel. This is also the default Svg unit

Negative

Some properties allow negative length values, but this may complicate the formatting model and there may be implementation-specific limits. If a negative length value cannot be supported, it should be converted to the nearest value that can be supported.

If a negative length value is set on a property that does not allow negative length values, the declaration is ignored.

Example

Default Units on CSS and attribute

This example demonstrates that:

  • the unit is mandatory in CSS (If the length does not have any unit, the property is discarded and takes the default values)
  • the unit default to pixel on attribute

Example code:

.box {
   width:10;
   height:10;
}
  • the html with :
    • a div where the css rule will apply
    • an img with width and height attribute without a length of 50 without unit
<div class="box">
   <img src="/_media/web/rss_icon.jpg" height="50" width="50" />
</div>

</code>

let box = document.querySelector('.box');
let styles = window.getComputedStyle(box);
let width = styles.getPropertyValue("width");
let height = styles.getPropertyValue("height");
console.log("The computed css width is "+width);
console.log("The computed css height is "+height);
let img = document.querySelector('img');
let imgStyles = window.getComputedStyle(img);
let widthImg = imgStyles.getPropertyValue("width");
let heightImg = imgStyles.getPropertyValue("height");
console.log("The computed img width is "+widthImg);
console.log("The computed img height is "+heightImg);
  • Result: we can see that:
    • the css width and height are not 10 but the default values: ie
      • the full available width
      • a zero height.
    • the img sizing has taken the default pixel unit

Documentation / Reference

Task Runner