How to usethe calc() function in CSS
Use the calc() function to get 100% height with padding and margin. To make sure the content fits within the designated space, set the height to calc(100% – (padding + margin)) to deduct the total padding and margin from the parent container’s height.
Example: In this example, we are using the above-explained approach.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >CSS 100% Height with Padding/Margin</ title > < style > html, body { height: 100%; margin: 0; } .container { height: calc(100% - 40px); padding: 30px; box-sizing: border-box; } </ style > </ head > < body > < div class = "container" style = "background-color: green;" > < h1 >calc() function</ h1 > < p > Here we are using the calc() function to achieve 100% height with padding. </ p > </ div > </ body > </ html > |
Output:
How to Set 100% Height with Padding/Margin in CSS ?
In this article, we’ll explore CSS layouts with 100% width/height while accommodating padding and margins. In the process of web page design, it is often faced with scenarios where the intention is to have an element fill the entire width and/or height of its parent container, while also maintaining appropriate padding or margins. However, achieving this seemingly uncomplicated objective can sometimes be difficult.
We have a few approaches to get CSS 100% height with padding/margin that are discussed in detail below:
- Using Box-sizing Property
- Using position Property
- Using the calc() Function
Contact Us