CSS Calculations

 

css-calculate

This is just meant to be a quick tip about how to use CSS Calculations. It is a really handy feature. The main way I use it is to combine percentage rules with set pixel rules. There are so many times I would prefer to percentages to define width, margin, padding, etc so that as the website sizes down it looks good at all possible sizes. However, consistency is king when designing websites. It can be really difficult to have consistent space between columns and sections when using percentages. As a result of this I find myself setting a width of 100% or a width of 50% and using a padding with a percentage as well to get a consistent space while still reaping the benefits of percentages. The problem is, this doesn’t work all the time. For example, on a recent project I wanted two elements to float next to each other. Both elements had a background image, so if I did the width: 50%; padding: 0 5% method the background images would but right up against each other.  What I really wanted was to determine a set pixel space in between the two elements, but still be able to use a percentage.

With CSS Calc you can do just that. What I ended up doing was setting the width to be 50 percent minus 20 pixels. Then adding a margin-left to the odd element of 20 pixels. It works like a dream. To learn more about CSS Calc Visit w3schools

Below is the CSS version of what I described above.

element {
width: calc(50% - 20px);
}
element:nth-child(odd) {
margin-left: 20px;
}
element:nth-child(even) {
margin-right: 20px;
}