CSS has changed a lot since I first learned it in 2010. When I started, very little of the above would make sense. Today, however, not only does it make sense, but it _works. _At least, mostly.

(We are talking about CSS here.)

The situation that birthed the above monster started when I inherited a project from a former developer. The main width of the website was 1200px wide, but this particular section was unique. It was a two-column layout with the right column being 40% of the screen width and the left column being 60%. The content inside the left column would have to match the width of the rest of the site. It’s easier to visualize than to explain:

The things we put up with when we do web dev.

The developer I inherited this problem from fixed this issue by creating ~16 media queries to adjust the size of the “???” section. Although it worked, that was not necessary. Instead, we can use CSS to figure it out.

To begin, we need to get the full width of the screen. This can be best captured with 100vw which is 100% of the viewport.

We then subtract the width of our site. In our example, it is 1200px wide. To do that, we write this:

.left-column {
    padding-left: calc(100vw - 1200px);
}

This leaves us with the combined size of the margin on either side of the 1200px box. We only need half of that, so we divide it.

.left-column {
    padding-left: calc((100vw - 1200px)/2);
}

(This is like computing the size of autoif you just did margin: 0 auto; )

Normally, this would be enough. The sections line up nice and tidy. However, the 1200px box has some additional internal margin so that the content isn’t flush against the screen on smaller resolutions. It has 2.5% margin on desktop, and 20px margin on tablet.

This is where the previous developer started using media queries. But why? We can just use the max()function, in which CSS will pick whatever is bigger.

.left-column {
    padding-left: calc(((100vw - 1200px)/2) + max(3%,20px))
}

(We used 3% here even though the above is 2.5% because it’s the margin of the width and 2.5% of 1200px is about the same as 3% of 100vw. Just roll with me.)

My Picasso-like illustration above doesn’t show it, but on mobile there is a 55px left and right margin inside the 1200px section. We need that to do that too. Again, we could use a media query for this, or we can wrap our formula inside another max() function.

.left-column { 
    padding-left: max(calc((100vw - 1200px)/2 + max(3%,20px)),55px)
}

If we explain that simply, we are getting the size of the screen (red), minus the content width (orange), divided in half (yellow), plus 3% or 20px (whichever is bigger) (green), or 55px (whichever is bigger) (blue).

#css3 #css #web-design

Making sense of max(calc((100vw - 1200px)/2 + max(3%,20px)),55px)
2.15 GEEK