djs22
djs22

Reputation: 1156

Vertical-Align Divs in HTML/CSS

I'm trying to create a header consisting of an h1 and a nav element. I want the bottom of the nav to be aligned with the bottom of the h1.

Here's what I've tried:

HTML

<header>
    <h1>Web site Header</h1>
      <nav>
         <ul>
          <li>one</li>
          <li>two</li>
          <li>three</li>
         </ul>
       </nav>
 </header>

CSS

header {vertical-align: bottom; width: 100%; height: 300px;}
h1 {vertical-align: bottom; float: left;}
nav {vertical-align: bottom; float: right;}
nav ul li {display: inline;}

I could do this by setting exact margins for my elements, but I thought this would be cleaner (if it's possible). Any advice on how to fix it/if it can be done?

Thanks!

Upvotes: 0

Views: 8840

Answers (2)

zzzzBov
zzzzBov

Reputation: 179284

It's possible to do in many different ways. Margins are designed for positioning, but if you'd rather not use margins or padding, you can use absolute positioning:

CSS:

header
{
  display: block;
  height: 300px;
  width: 100%;
}
h1
{
  float: left;
  margin: 0;
  height: 32px;
}
nav
{
  display: block;
  height: 32px;
  position: relative;
}
nav ul
{
  bottom: 0;
  list-style: none;
  margin: 0;
  padding: 0;
  position: absolute;
  right: 0;
}
nav ul li
{
  display: inline-block;
}

HTML:

<header>
  <h1>Web site Header</h1>
  <nav>
    <ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    </ul>
  </nav>
</header>

This relies on knowing the height of the header, and setting both the header and the nav to the same heights/margins.

Upvotes: 0

Filip Dupanović
Filip Dupanović

Reputation: 33700

As clean as it can get:

<style>
    header > * { display: inline-block; }
    nav li { display: inline; }
</style>

Direct header descendants are now inline blocks, i.e. they don't push surrounding content to flow beneath them, yet they can still utilize the margin and padding property as blocks.

Upvotes: 1

Related Questions