HTML and CSS Reference
In-Depth Information
Converting Pixels to Percentages
The next step is to convert all of our horizontal layout-based pixel values to percentages. By
“horizontal”, I'm referring to elements like left and right margins and padding, widths, and
right and left positioning. The percentages we're going to replace them with will be percent-
age equivalents for the existing values. This means the layout will not change for standard,
wide-screen desktop users.
Percentages in CSS are always relative to something. In the case of widths and left and right
margins, these values are relative to the parent element's width. So if you have an element
that is 100 pixels wide, and you add 10% of left padding to a child element, that 10% will
compute to 10 pixels.
Let's begin with our .logo element, which is a child element of one of our .center-
global elements (in this case, the one inside <header> ):
.logo {
float: left;
margin-left: 14.2156862745098%;
margin-top: -34px;
position: relative;
top: 34px;
transform: translateX(-800%);
animation: logomove 2s ease-out 1s 1 normal forwards;
}
Here we've changed the value for the margin-left property from 145px to a percentage value.
This percentage is arrived at using the following formula:
target value / context * 100
In the case of the logo's left margin, the target value is 145 pixels. This was the amount of
left margin we had on the element to begin with. We then divide that number by the parent
element's width (the “context”). The parent element, as just mentioned, is 1020 pixels when
it's at its widest. That calculation gives us a value of 0.142156862745098. The last thing we
do is multiply this number by 100 (which moves the decimal place over two places), giving
us our final desired percentage―which in this case is about 14.22%.

Search WWH ::

Custom Search