7

I constantly find myself having to vertically center both the logo and main menu in a full-width header. Is there a widely accepted method to handle this?

enter image description here

drake035
  • 3,955
  • 41
  • 119
  • 229
  • Here's a related question that was useful for me: http://stackoverflow.com/questions/22429003/right-aligning-flex-item –  Mar 31 '17 at 04:38

3 Answers3

3

#header {
  box-sizing: border-box;
  background: #ffc301;
  padding: 10px 15px;
  display: table;
  width: 100%;
  height: 70px;
}

.logo {
    background: #000;
    text-align: center;
    width: 70px;
    color: #fff;
}

.logo,
.menu {
  vertical-align: middle;
  display: table-cell;
}

.menu ul {
  text-align: right;
}

.menu ul li {
  display: inline-block;
  vertical-align: top;
}
<header id="header">
  <div class="logo">Logo</div>
  <nav class="menu">
    <ul>
      <li><a href="#">Item 1</a></li>
      <li><a href="#">Item 2</a></li>
      <li><a href="#">Item 3</a></li>
      <li><a href="#">Item 4</a></li>
    </ul>
  </nav>
</header>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
2

You can use flexbox to get it with justify-content: center; and align-items: center; properties.

#header {
  box-sizing: border-box;
  background: grey;
  padding: 10px 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 70px;
}

.logo {
    background: black;
    text-align: center;
    width: 70px;
    padding: 15px;
    color: #fff;
}

.menu{
  flex: 1;
  text-align: right;
}

.menu ul li{
  display: inline-block;
  text-decoration: none;
}

a{
  text-decoration: none;
}
<div id="header">
  <div class="logo">logo</div>
  <nav class="menu">
    <ul>
      <li><a href="#">item#1</a></li>
      <li><a href="#">item#2</a></li>
      <li><a href="#">item#3</a></li>
    </ul>
  </nav>
</div>
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
0

You can use "display:inline-block" property and shorten your code as simple as below..

HTML:

<header>
<div class="logo"><img src="logo.png" /></div><!--
--><nav class="menu">
<ul>
  <li><a href="#">Item 1</a></li><!--
  --><li><a href="#">Item 2</a></li><!--
  --><li><a href="#">Item 3</a></li><!--
  --><li><a href="#">Item 4</a></li>
</ul>
</nav>
</header>

CSS:

header{
background-color: grey;
box-sizing:border-box;
display:inlnie-block;
padding:10px 15px;
width:100%;
}
.logo,.menu{
display:inline-block;
font-size:0;
vertical-align:middle;
}
.logo{
text-align:left;
width:30%;
}
.logo img{
max-width:100%;
}
.menu{
text-align:right;
width:70%;
}
.menu ul li{
display:inline-block;
font-size:0;
vertical-align:middle;
}
.menu ul li a{
font-size:14px;
line-height:18px;
text-decoration:none;
}