While styling with CSS, I've noticed that the padding property can easily achieve the same affect as the height property... however the padding property keeps my text nice and center, whereas the height property forces me to add other CSS rules / adjust line height.
Is it "wrong" or against commonly used CSS standards to ditch the height property and use padding for the height of an element instead?
What repercussions might this bring?
Both height and padding inherently control the height of an element. I would have to disagree that using padding is wrong, but rather depends on the specific use case.
Use height when you need a fixed container size.
Use padding when you don't need a fixed container height, but want to add whitespace.
Use min-height and max-height for a hybrid approach.
You can use the box-sizing
property:
By default, the width and height of an element is calculated like this:
- Width + Padding + Border = Actual width of an element
- Height + Padding + Border = Actual height of an element
This means: The element's border and padding are added to the element's specified width/height.
Using the box-sizing
property will allow you to include an elements padding and border as part of it's total height and width.
When you set box-sizing: border-box;
the element's padding and border will be included as a part of it's total width and height.
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
}
<div class="div1">This div is smaller (width is 300px and height is 100px).</div>
<br>
<div class="div2">This div is bigger (width is also 300px and height is 100px).</div>
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
box-sizing: border-box;
}
.div2 {
width: 300px;
height: 100px;
padding: 50px;
border: 1px solid red;
box-sizing: border-box;
}
<div class="div1">Both divs are the same size now!</div>
<br>
<div class="div2">Hooray!</div>
Yes, it is wrong to use padding to control the element height.
height
controls the actual height of the element (basically the distance from border-bottom
to border-top
) whereas padding
controls the distance between the content and the border.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With