I have a <div>
that contains a <label>
, well, adding the CSS property display: inline-block
to <label>
increases the margin or the margin padding
of it (I don't know why), here is the example:
document.addEventListener("DOMContentLoaded",function() {
var label = document.getElementById("label");
setTimeout(() => {
label.style.display = 'inline-block';
label.innerHTML += ', algo traviesa ;)';
}, 2500);
});
* {
padding: 0;
margin: 0;
}
#cont {
padding: 20px;
background: #dedede;
}
#label {
padding: 10px;
background: #fff;
color: #000;
}
<div id="cont">
<label id="label">Soy una etiqueta</label>
</div>
This is because tags
label
areinline
default elements, which means that these elements cannot have height or width and are expressly adjusted to the content of the element.Example:
If you notice, both width (
width
) and height (height
) are not applied to the taglabel
.The property
padding
has a bit of a curious effect with elementsinline
, since it only takes into account the left and right side but not the top and bottom when considering space with other elements.Example:
As you can see in the example above, it only takes into account
padding
both to the left and to the right of the taglabel
, but not above or below it to position the rest of the elements.Therefore, why when we use the property
inline-block
increasespadding
?Actually it doesn't increase, but by setting an element as
inline-block
it means that it behaves like an elementinline
(it can be with other elements on the same line, it adjusts to the content, etc...) but at the same time it takes into account the properties of the elementsblock
(it takes into account properties such as height and width,padding
on all its sides, etc...).That is to say, the
padding
does not really increase, but rather it is applied to all its sides and that is why it gives an effect that it is increasing when we add the property to itinline-block
.Let's see the previous example but using
inline-block
in the taglabel
:As you can see in this last example, the
padding
is applied to the elementlabel
and the tagspan
honors thepadding
.