How to limit the size of an element with padding in CSS?
I want to create an HTML page with a <div>
that has a fixed height of 450px
to save texts and other elements. To do this, I created a class with the following properties in CSS.
.minhaClasse{
height: 450px;
max-height: 450px;
}
The problem is that the property max-height
does not work when I add padding
to the element. On some HTML pages, I need to add a padding-top
in the element to scroll down the text on the page.
See the example below:
.minhaClasse{
height: 450px;
max-height: 450px;
}
<body align="center">
<div class="minhaClasse" style="padding-top: 100px;">
Meu texto dentro da DIV 100px abaixo <br>
(gostaria que a div permanecesse com 450px de altura)
</div>
</body>
As you can see, the size of <div>
exceeds the height limits of the element. What I want to know is, how can I limit the height of my element even by adding a padding
to it ?
1 answers
If you have height: 450px;
you do not need max-height: 450px;
, unless you are using some means of diplay
other than block
, which seems unlikely for your case, to solve it would be enough to use box-sizing: border-box;
or with backward compatibility:
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
The box-sizing property by default uses the value content-box
, each value has a box-model behavior, which will behave differently as per padding
, border
, margin
and the content itself
Box-sizing: content-box
This is the value property default, causes the element to have the height set by the width and height and content included (limited) in the measures, but does not "limit" the padding
, border
e margin
For example if an element has height: 300px;
and adds a padding-bottom: 50px;
the height will be height: 300px;
If it only has the height and the padding is zero, but the content passes from 300px
the element will still have 300px
, the content will only "leak out" of the box-model, because it has passed from limit.
Box - sizing: padding-box
The width, height, and padding properties include (are limited to) box-model
, but will not include border
or margin
.
Box-sizing: border-box
The width and height Properties padding
and border
include (are limited), but the margin
property will not be included.