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()`.
0 Comments