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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With