Reputation: 141
It seems like vertical aligning in CSS is a common problem but I can't seem to work through this. I'm trying to create a basic header (recreating the Youtube video page for practice), and I can't get the search form and logo to vertically align within the header div
.
Here's a JSFiddle of what I did: https://jsfiddle.net/eternal/qp6cqtaj/
I tried to copy a solution I found that used pseudo-classes, but so far it didn't work.
HTML
<div class="header">
<div class="centered">
<img src="http://i.imgur.com/EFkps0m.png"></img>
<form>
<input type="text">
</form>
</div>
</div>
CSS
.header {
min-width: 60px;
width: auto !important;
white-space: nowrap;
height: 50px;
}
.header:before {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
}
.centered {
display: inline-block;
vertical-align: middle;
width: 100%;
height: 100%;
}
.centered * {
display: inline-block;
}
.header form {
left: 25px;
width: 65%;
max-width: 583px;
height: 50%;
}
.header input {
width: 100%;
}
Upvotes: 2
Views: 743
Reputation: 371271
Save yourself a lot of code writing and maintenance. Use a CSS Flexbox.
HTML
<div class="header">
<img src="http://i.imgur.com/EFkps0m.png">
<form><input type="text"></form>
</div>
CSS
.header {
display: flex;
justify-content: flex-start;
align-items: center; /* this one line vertically centers all child elements */
height: 50px;
}
.header > form {
width: 65%;
margin-left: 25px;
}
.header > form > input {
width: 100%;
}
https://jsfiddle.net/qp6cqtaj/5/
A few notes:
justify-content
and align-items
properties.<img>
tag is a void element. No closing tag required. You can remove the </img>
.Upvotes: 2
Reputation: 11328
Actually, you can simplify your HTML, no need for centered div:
<div class="header">
<img src="http://i.imgur.com/EFkps0m.png"></img>
<form>
<input type="text">
</form>
</div>
And, since you already using fixed height:
.header {
min-width: 60px;
width: auto !important;
white-space: nowrap;
height: 50px;
}
.header form {
left: 25px;
width: 65%;
max-width: 583px;
height: 50px;
line-height:50px;
display:inline-block;
margin:0;
padding:0;
vertical-align: middle;
}
.header input {
width: 100%;
}
.header img {
display:inline-block;
vertical-align: middle;
}
Demo: http://jsfiddle.net/74bhq5bj/2/
line-height on form element helps, in this case.
Upvotes: 0
Reputation: 2008
Add vertical-align to .centered *
.centered * {
display: inline-block;
vertical-align: middle;
}
https://jsfiddle.net/qp6cqtaj/2/
Upvotes: 1