DEV Community

Andrei Navumau
Andrei Navumau

Posted on • Updated on

Using calc() in CSS responsive design

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:

div in browser

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:

  1. We take 100% of the width of the icon's container. It's 480px.
  2. Then we deduct the width of all icons, which is 5*51px = 255px.
  3. This gives us the remaining spacing in the container. We need to divide it by 4. Because we have 4 gaps between 5 images.
  4. 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)

Collapse
 
mchl18 profile image
morefox

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/

Collapse
 
mchl18 profile image
morefox

and not worry about calculating margins

Collapse
 
tyzia profile image
Andrei Navumau

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.

Collapse
 
mchl18 profile image
morefox

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

Collapse
 
risyandi profile image
Risyandi

Nice, that very simple.

Collapse
 
askthepunkuzz profile image
Punkuzz

Short and simple.