How to use calc() in css styling
Last time I made a post about my struggle with responsive design and adding multiple breakpoints and doing a lot of math in excel. The post can be found here. Thanks to ArcCosine's comment, I learned about calc() function in CSS. I applied it in my css file and it worked like a charm!
Here is the html code:
div id=A div id=B img img img img img /div /div
In browser this looks like this:
To keep it short: I have 5 images of social icons, 51px fixed width each. The width of their container (div id=B) is 480px. I would like to calculate margin between icons responsive to screen size. So my css calculation is like this:
#B img { margin-right: calc((100% - 255px) / 4); } #B img:last-child { margin-right:0 }
Just a tiny explanation:
- We take 100% of the width of the icon's container. It's 480px.
- Then we deduct the width of all icons, which is 5*51px = 255px.
- This gives us the remaining spacing in the container. We need to divide it by 4. Because we have 4 gaps between 5 images.
- So we have the length of our margin-right. Last icon's margin we set to zero.
Now, if we resize the screen, container's width will be, for instance, 460px and margin-right will be recalculated based on the new container's width.
That short, that simple. Thank you ArcCosine, once again.
Top comments (6)
Another way of positioning these in a responsive manner would be flexbox in combination with margins:
css-tricks.com/snippets/css/a-guide-to-flexbox/
and not worry about calculating margins
Thank you, morefox. Flex - is a completely new thing for me, but I have already tried it out and I love, how simple is to code with flex.
there are also frameworks such as bulma.io and bootstrap v4 also uses flexbox, a tool that has been long awaited by frontend devs for solving the most simple layout and grid problems
Nice, that very simple.
Short and simple.