Search code examples
cssnav

Display:block does not stack nav element


I'm having a little trouble getting the nav element to truly behave like a block element. I tried making a menu out of nav and a tags instead of the usual ul and li tags. That did not go as planned. My menus show up after each other as if the display:block css have no effect. I'd like to get the menus to stack, not show up after each other.

The HTML:

<nav id="mainmenu">
    <a href="#">Item1</a>
    <a href="#">Item2</a>
    <a href="#">Item3</a>
<nav>
<nav id="submenu">
    <a href="#">Item1</a>
    <a href="#">Item2</a>
    <a href="#">Item3</a>
<nav>

The CSS:

nav{
    display: block;
}

EDIT:

This is how I'd like it to be setup but I'd prefer to float the a element so I don't get the spacing issue with inline-block.

http://jsfiddle.net/Kpv5H/2/

I still don't understand why floating the a tag makes all a tags show up inline when the nav element is block?

http://jsfiddle.net/Kpv5H/4/

If I unfloat the a tag they align correct but I lose the padding on top and bottom of the a tag. If I add display:block to correct that all a tags stack on top of eachother. If try to correct that with a float:left the show up inline.

Inline-block on the a tag seems to fix it but then I get the spacing issue instead.

Is there a way to stack the nav elements and float the a elements and still preserve the padding to the a element?


Solution

  • EDITED: *(after adding more details by OP)*

    BY USING INLINE-BLOCK TECHNIQUE:

    By using inline-block if you set font-size:0px; in nav (the main container having inline-block elements) then you will not get the extra spacing causing by inline-block

    SEE DEMO

    Without adding font-size:0px; in nav it will look like this:

    SEE DEMO

    BY USING FLOAT TECHNIQUE:

    you need to add overflow:hidden and a width to prevent your nav element to be float.

    See the changes in your CSS below:

    nav {
        display: block;
        overflow:hidden; /* Added */
        width: 100%; /* Added */
    }
    
    nav a {
        float: left;
        padding: 2em;
    }​
    

    SEE DEMO