Home > database >  padding in the Header or P tag doesn't work correctly with em unit
padding in the Header or P tag doesn't work correctly with em unit

Time:01-30

I have a problem when using the em unit for padding. I have a div with a h5 tag

<div id="myDiv">
    <h5>
        my header
    </h5>
</div>

and with this CSS

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}


#myDiv{
    font-size: 32px;
}

 #myDiv h5{
        background-color: red;
        color: white;
        padding: 1em;
    }

I should expect the padding to be equivalent to 32px but when I open Inspect on the browser I see padding calculated to the below image

enter image description here

padding size is 13.280px

but when I use div or section instead of h5 that work fine.

CodePudding user response:

em depends on the font-size of the element that it is on. This means that if you have the following;

.example {
    font-size: 20px;
    padding: 4em;
}

then the padding would be 80px.

By default, div and section tags have a default font size of 16px. An h5 has a font size of 13.28 px by default. Source. Use h4 instead (it has a default of 16px) or set the h5's font-size to 16px.

#myDiv h5{
    background-color: red;
    color: white;
    font-size: 16px;
    padding: 1em;
}

NOTE: These values might differ slightly between browsers.

You can see this in action here;

let h1 = document.querySelector("h1");
let div = document.querySelector("div");
let section = document.querySelector("section");
let h5 = document.querySelector("h5");
let h4 = document.querySelector("h4");

console.table({ "h1": window.getComputedStyle(h1).getPropertyValue('font-size'), "div": window.getComputedStyle(div).getPropertyValue('font-size'), "section": window.getComputedStyle(section).getPropertyValue('font-size'), "h5": window.getComputedStyle(h5).getPropertyValue('font-size'), "h4": window.getComputedStyle(h4).getPropertyValue('font-size') });
<h1>Hi</h1>
<div>Hi</div>
<section>Hi</section>
<h5>Hi</h5>
<h4>Hi</h4>

  • Related