Understanding calc() in CSS

The calc() function in CSS allows you to perform mathematical operations on values dynamically. This is particularly useful when working with responsive designs, ensuring elements adjust based on different screen sizes and available space.

Supported Operators

Unsupported Operations

While calc() is powerful, it has limitations. You cannot use it for:

What is vw?

vw (viewport width) is a CSS unit that represents a percentage of the total width of the viewport. For example:

It is commonly used in responsive designs to ensure elements scale with the browser width.

Examples

Here are some examples of how you can use calc() in CSS:

1. Making a div take full width minus padding

div {
    width: calc(100% - 20px);
}

2. Centering an element

.box {
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 50px);
    width: 100px;
    height: 100px;
}

3. Sidebar taking one-third of the screen width

.sidebar {
    width: calc(100vw / 3);
}

4. Text resizing dynamically

h1 {
    font-size: calc(1rem + 2vw);
}

5. Flexible button width

button {
    width: calc(50% - 10px);
}

6. Column layout

.column {
    width: calc(33.33% - 20px);
    float: left;
}

7. Combining percentages and pixels

.box {
    width: calc(70% - 50px);
}

Assignments

1. Create a Responsive Card

Make a div that takes 70% of the parent width but also subtracts 30px for margins.

2. Design a Sticky Header

Create a header that is always 60px tall, ensuring the content starts 60px from the top.

3. Build a Responsive Sidebar

Make a sidebar that takes up one-fourth of the screen width and adjusts dynamically.

4. Create a Dynamic Font Size

Make a heading where the font size increases as the viewport width increases.

5. Flexible Grid Layout

Build a grid where each column takes one-third of the available space but subtracts 20px for margins.