The browser support for different CSS features has improved significantly over the past few years. Although vertically centering a paragraph is something that we can do quite easily, there are still some crucial features that we don't have. Media queries are based on the browser's viewport and screen resolution. However, sometimes we may need container-queries. These are only available under certain feature flags. Today, we will use the Fab Four technique to apply a border-radius to an element based on its container dimensions, not the screen width.
You can use various CSS functions such as min, max, and calc to determine if a particular CSS rule should apply and compare it to the container element's dimension instead of the device viewport.
What is CSS? And How It Works!, Source: Youtube, Create a Pro Website
We want to ensure that the card containers are less than 400px in width.
What's the story? First, we need to understand what 100% is doing. The setting width: 100% to a CSS element will, in most cases, expand it to the entire width of the container. If 100% is used within a min function, the container will always return its original width.
Minimum Detectable Effect Calculation, Source: Youtube, Richard Gallenstein
The * 9999 part is used to ensure that we are always above or below the max value. We might get something in the middle.
We have the following result because we have a min-function:
This is crucial because the CSS parsing engine doesn't like how we try and define the border-radius using the min or max functions. So we use this little trick.
Our CSS parsing engine is used to calculate 100%.
19. Media queries? Source: Youtube, F8 Official
This percentage would equal the container's width, not the screen width, which can be used in media queries.
Depending on the situation, the Fab Four technique can be used in many cases. A specific rule should be used when the container's width falls below a breakpoint.
This calculation can be complicated, even if you're familiar with it.
CSS utility classes, Source: Youtube, Fredrik Christenson
We can extract SASS mixins or utility functions from various CSS-inJS libraries (like styled-components).
As the web evolves, we will see more features such as container-queries in web browsers. We can still use techniques such as the Fab Four to meet specific application requirements that don't always seem straightforward.
Hope this article is helpful to you, thanks for reading.