How to use vertical-align: middle; properly?

不羁岁月 提交于 2019-12-07 15:39:33

问题


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.


回答1:


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.




回答2:


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; }


来源:https://stackoverflow.com/questions/2439267/how-to-use-vertical-align-middle-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!