Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically align text inside a div with percentage height and width?

I know how to align text vertically inside a div, but I am unsure on how to do it if the div has a percentage height and width. Here is my code:

    <div id="header">
        <h1>Home</h1>
    </div>

    #header {
        background-color: red;  
        color: white;
        text-align: center;
        vertical-align: middle;
        width: 100%; 
        height: 15%;
    }

Now on my webpage the text in the div has been aligned correctly horizontally but not vertically. How do I fix this problem? Can you also try to explain your answers and keep them as simple as possible please (I'm still relatively new at HTML/CSS). Thank you.

like image 335
Pancake_Senpai Avatar asked Jan 09 '23 22:01

Pancake_Senpai


1 Answers

You can use the flexbox model to easily center things.

Just add the following rules to your container:

display:flex;
justify-content: center; //horizontal centering
align-items:center; //vertical centering

FIDDLE

Note this is probably a more general solution than what you expected, but what's really cool about flexbox is that it works in many different cases, including yours (example with an h1 tag here).

like image 185
Sir Celsius Avatar answered May 01 '23 16:05

Sir Celsius