Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

padding size is 13.280px

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading