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:
- number is positive or negative
- unit is a unit identifier
- After a zero length, the unit identifier is optional,
- In CSS, the unit is mandatory (but not in html attribute see the default unit demo
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 :
- 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>
- The computed width and height for the div box is shown below via this javascript
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);
- The computed width and height for the image is shown below via this javascript
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