3

I want to have my list (nav) align to the center of an image (logo). I tried using vertical-align: middle;, but I couldn't get it to work when I floated the images left and right.

Here's my code:

HTML:

<div id="head">
    <img id="logo" src="logo.png" />
    <ul id="nav">
        <li><a href="#">Item 1</a></li>
        <li><a href="#">Item 2</a></li>
        <li><a href="#">Item 3</a></li>
    </ul>
</div>

CSS:

#head {
    margin-top: 2px;
    width: 100%;
}
    #logo {
        float: left;
        }

    ul#nav {
        float: right;
        }

        ul#nav li {
            display: inline;
            list-style-type: none;
            }

I took all the vertical-align: middle;'s from where I put them (I tested it in each element, even though it was only supposed to be applied to #logo, from what I've read.)

Anyways, any help would be appreciated.

Andrew
  • 12,172
  • 16
  • 46
  • 61
  • You're lucky you're using an image. That means you already know the height of the div. You get to use other fixed-height solutions like line-height applied to the
      . On the other hand, I'm dealing with fluid height, and am still looking for an answer...
    – syockit Apr 17 '11 at 13:49

2 Answers2

2

Vertical-align:middle aligns the median of child element to the median of parent element. If all child elements have float:left, then the parent has a height of 0px and hence its median is above the child elements.

So, you might add a <br style='clear:both' /> after your menu and the DIV will finally get its vertical size.

naivists
  • 32,681
  • 5
  • 61
  • 85
  • I added the `
    `, set a height attribute on `#head`, and put `vertical-align: middle` on the `#logo` and `#nav` IDs, but they still align to the top.
    – Andrew Mar 13 '10 at 18:00
  • But actually, why do you need `float:left` for the UL element? – naivists Mar 13 '10 at 18:12
  • 1
    anyway, floated elements are 'taken out' of the regular text stream, so "vertical-align" attribute does not apply to them. A simple workaround to align the figures is to set `padding-top` of the image. – naivists Mar 13 '10 at 18:21
  • if it's variable height, padding-top can't be used. Any other solutions? – syockit Mar 05 '11 at 10:11
  • I hate so much Web because of tricks like `
    `
    – Olivier Pons Dec 03 '15 at 10:20
0

table with single row comes handy here.

<div id="head">

<table>
<tr>

<td>
  <h1>Fluid Heading</h1>
</td>

<td style="width: 5%">
  <img id="logo" src="logo.png" />
</td>

<td style="width: 5%">
  <ul id="nav">
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a></li>
  </ul>
</td>

</tr>
</table>

</div>

CSS:

.head td { vertical-align: middle; }
Ninad
  • 957
  • 7
  • 19