I know this question has been asked to death but I can't seem to make any of the solutions work. Please be sympathetic, I have been trying for days!
I want to vertically centre everything in the header element at the centre of its height. Eventually I plan on heaving a little logo, title and navigation links in the header. While the logo and title are floated to left, the navigation links need to stay floated to the right.
Why is vertical alignment made SO HARD in html/css!
I'd prefer a solution that does what I want directly and not consequently by fixing/padding/adjusting things around the elements but if that is the only way then fine. Here is what I have so far.
* {
border: 1px solid black
}
header h1 {
display: inline;
}
header nav {
display: inline;
float: right;
}
<header id='header'>
<h1>Obla Di Obla Da</h1>
<nav id="nav">
<a href="https://google.com">Evil</a> |
<a href="https://duckduck.com">Not Yet Evil</a>
</nav>
</header>
Floats and inline elements are a nightmare when it comes to the vertical axis. You should take a look at using Flexbox - it really excels with intra-element positioning - namely its align-items: center
property value (assuming you're using a flex row
and not a flex column
at which point you'll want justify-content: center
)
Take a look at this snippet
* {
border: 1px solid black
}
#header {
background: #0095ee;
color: #fff;
}
.flex {
display: flex;
}
.align-center {
align-items: center;
}
.space-between {
justify-content: space-between;
}
<header id='header' class="flex align-center space-between">
<h1>Obla Di Obla Da</h1>
<nav id="nav">
<a href="https://google.com">Evil</a> |
<a href="https://duckduck.com">Not Yet Evil</a>
</nav>
</header>
The other way that you see quite a bit is to use an absolute
position
on a a child, set the top
to 50%
, and set it's transform
X translation to -50%
, though this is less common now, due to the expanse and ease-of-use of flex, and the inherent issues that come with removing elements from the document flow.
.parent { position: relative; }
.vertical-child {
position: absolute;
top: 50%;
transform: translateX( -50% );
}