Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS how to round of percent values to whole number pixel

Tags:

html

css

In CSS, when width, height, margin etc use percentages, the result will sometimes come back with a fractional pixel length, e.g. 100.25px. I want to know how to round off this to the next integer. This seems to be quite a common issue; I've searched around it a lot, but have yet to find a solution.

For example, in the code below, Chrome rounds 50.6px to 50px, which isn't the mathematical standard.

background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f9e7d0), color-stop(72%,#f9e7d0), color-stop(72%,#207cca), color-stop(72%,#b08b5b), color-stop(100%,#b08b5b));

In JavaScript this would be achievable using the ceil function, but can it be done in pure CSS?

like image 716
Chintan_chiku Avatar asked Mar 05 '14 07:03

Chintan_chiku


People also ask

Can you do decimal pixels in CSS?

Although you can use decimal places in CSS like 100.0% in reality it best to keep to real numbers for percentages and only upto one decimal place with standard linear integer values. Your 2.9… probably would be read as 3.

What is the difference between pixel and percentage in CSS?

Pixel is a static measurement, while percent and EM are relative measurements. Percent depends on its parent font size. EM is relative to the current font size of the element (2em means 2 times the size of the current font).

Can you use percentages in CSS?

The <percentage> CSS data type represents a percentage value. It is often used to define a size as relative to an element's parent object. Numerous properties can use percentages, such as width , height , margin , padding , and font-size . Note: Only calculated values can be inherited.

Can you have fractional pixels?

Yes, you can specify fractional pixels. As this has been part of CSS since the very first version, it should be well supported by any browser that supports CSS at all.


1 Answers

Browsers round fractional pixels automatically - some up, some down; this is hard coded into the browsers so there's no way to force it to do one or the other with CSS.

A more indepth look at how different browsers treat fractional pixels can be found here.

like image 143
Sinister Beard Avatar answered Oct 26 '22 21:10

Sinister Beard