Explain Codes LogoExplain Codes Logo

How to get rid of extra space below svg in div element

html
css
responsive-design
browser-compatibility
Nikita BarsukovbyNikita Barsukov·Oct 20, 2024
TLDR

Banish extra space beneath SVG in a div by adjusting vertical-align to middle, as shown below:

svg { vertical-align: middle; /* Sayonara, extra space */ }

This aligns the bottom of your SVG to the middle of the line height. Voilà! No more space.

Understanding the extra space saga

Culprit: Character descenders

SVGs, inherently inline elements, are affected by text alignment rules. Space is reserved below their baseline for hypothetical character descenders (think the "y" in "Sydney"). Even if our SVGs are rock bands without any "Y", the stage (space) is set, expecting a surprise entry.

Solution: Play the display card

Change display to block to tell SVG "You're no text, you're a rockstar!", stopping it from reserving space for descenders:

svg { display: block; /* You're a rockstar now */ }

Now, your SVG within its parent DIV is a full house with no room for unwanted space.

Preemptive strike: CSS resets

Applying CSS resets gives you a clean slate, getting rid of browser-default styles. This first move might make all the difference in extra-space chess:

* { margin: 0; /* No interior design, please */ padding: 0; /* Maintain your physical boundary */ box-sizing: border-box; /* Good fences make good neighbors */ }

MVP: developer tools

Press F12 and conquer unexpected spacing. Developer tools help you identify the hidden enemy and devise your strategy.

Must-have adjustments

Browser compatibility

Test your display hacks on Firefox, Chrome, Safari, Edge, and yes, even IE (if you're feeling brave!). Check for universality, given each browser's unique behavior with SVGs.

Quick inline-styling adjustments

An awesome band needs a soundcheck. Likewise, you might need trial fixes. Apply inline styles temporarily to tweak SVG's height and background color:

<div style="height: 50px; background: #f3f3f3;"> <svg style="height: 100%; display: block;"></svg> </div>

Harmonious heights

For aesthetics, SVG and DIV heights should match. Remember, uniformity can help your design hit the high notes!