Using calc in CSS

Using calc in CSS



Here’s a complete example with an introduction, appropriate HTML and CSS tags, and a similar task you can try.

### Introduction:
The following example demonstrates how to center an element horizontally using the `calc()` function in CSS. The `calc()` function allows dynamic calculations for margins, widths, or any other property that requires values based on arithmetic operations. In this case, we subtract half of the element's width from 50% of the available space to center it.

### HTML & CSS Example:

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Center an Element</title>
  <style>
    .element {
      margin-left: calc(50% - 100px); /* Moves the element to the center */
      width: 200px;
      height: 100px;
      background-color: lightblue;
      text-align: center;
      line-height: 100px;
      border: 1px solid #333;
    }
  </style>
</head>
<body>
  <div class="element">
    I am centered!
  </div>
</body>
</html>
```

### Similar Task:
Now, try this challenge: Center an element **vertically** using `calc()`. 









<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dynamic Width Calculation</title>
  <style>
    .element {
      width: calc(50% - 20px); /* Width is 50% of the viewport minus 20px */
      margin-left: calc(50% - (50% - 20px) / 2); /* Centers the element dynamically */
      height: 100px;
      background-color: lightblue;
      text-align: center;
      line-height: 100px;
      border: 1px solid teal; 
    }
  </style>
</head>
<body>
  <div class="element">
    I have a dynamic width!
  </div>
</body>
</html>

Code on Git



Contact us for software training, education or development










 

Post a Comment

0 Comments

Me