DEV Community

Cover image for CSS functions - Learn about CSS function 2022
Modern Web
Modern Web

Posted on

CSS functions - Learn about CSS function 2022

Hey, I hope you are doing great. In this article, we'll talk about CSS functions. So without wasting time let's see what are these.

CSS Functions

CSS functions are used as a value for various CSS properties. So basically we use it to evaluate some of the CSS values. Let's see some of the functions.

1. attr()

This function is used to access value of the element's attributes. Let's understand it with the example.

<div data-bg="black"></div>
Enter fullscreen mode Exit fullscreen mode
div{
    width: 100px;
    height: 100px;
    background: attr(data-bg);
}
Enter fullscreen mode Exit fullscreen mode

You can see we have a "div" with "data-bg" a custom attribute and now I can access its value inside CSS using attr(). So, that's how you can do a lot of fun stuffs. 

So the output will be something like this.

output

2. calc()

After attr() we have calc(). As the name suggests, it helps in performing calculations for CSS values. This can be useful when we want to do precise calculation.

<div class="box"></div>
Enter fullscreen mode Exit fullscreen mode
.box{
    width: calc(100px * 5 - 50px);
    height: calc(100px - 30px);
}
Enter fullscreen mode Exit fullscreen mode

In the above code I used calc() to set div's width and height.

output

3. max()

Then we have max(), It takes two value and use the largest value for that CSS property. This can be useful in making responsive width and heights.

<div class="box"></div>
Enter fullscreen mode Exit fullscreen mode
.box{
    width: max(50%, 500px);
    height: max(60%, 300px);
}
Enter fullscreen mode Exit fullscreen mode

The div will have the maximum possible width and height in this case, if 50% is greater than 500px than its width will be 50% otherwise it will be 500px, same for height also.

4. min()

And the last but not least, we have min(), It takes two value and use the smallest value for that CSS property. This is opposite of max().

<div class="box"></div>
Enter fullscreen mode Exit fullscreen mode
.box{
    width: min(50%, 500px);
    height: min(60%, 300px);
}
Enter fullscreen mode Exit fullscreen mode

So the output of this will be exact opposite to our max(). It will set the smallest value as its width and height.

That's it. We do have some more functions but they are specific for properties. If you do have any doubt feel free to ask me in comments or you can join my discord server. We'll talk there.
Also, if you want to master web development, make sure to follow me on my Instagram and YouTube.

With that all. Thanks for reading 😎

Discussion (0)