Decimal Places in CSS Width: Respected or Rounded?
When crafting CSS designs, you may wonder if decimal places in CSS widths are honored or rounded. Whether the browser respects or ignores the decimal places depends on whether you're dealing with percentage or pixel values.
Percentage Widths
For percentage widths, the decimal places are fully respected. A width of 49.5% will occupy 49.5% of the available space. For example:
.percentage { width: 49.5%; }
Pixel Widths
In contrast, decimal places for pixel widths are not respected. They are always rounded to the nearest whole number. A width of 122.5px would become 123px. For example:
.pixel { width: 122.5px; }
To illustrate the difference, consider the following example:
#outer { width: 200px; } #first { width: 50%; height: 20px; background-color: red; } #second { width: 50.5%; height: 20px; background-color:green; } #third { width: 51%; height: 20px; background-color:blue; }
<div>
Here, the first block is 50% of the available space. The second block is 50.5% of the available space. But since decimal places are not respected for pixel widths, it rounds to 51px. The third block is 51% of the available space, which becomes 102px.
The above is the detailed content of Do CSS Widths Respect Decimal Places: Percentage vs. Pixel?. For more information, please follow other related articles on the PHP Chinese website!