magnattic
magnattic

Reputation: 12998

Make first and last child occupy remaining horizontal space

I need a horizontal list of links where the elements are only as wide as necessary (based on text width), but the first and last element occupy all the remaining space:

enter image description here

I know how to do it so that the last element stretches, but I have no clue how to divide the space between the first and last element equally.

This is how far I got: (Fiddle)

<ul id="menu" class="clearfix">
    <li class="entry">
        <a href="Index.html">
            Home
        </a>
    </li>
    <li class="entry">
        <a href="Osteopathie.html">
            Osteopathie
        </a>
    </li>
    <li class="entry">
        <a href="Behandlung.html">
            Behandlung
        </a>
    </li>
    <li class="entry">
        <a href="Schwangerschaft.html">
            Schwangerschaft
        </a>
    </li>
    <li class="entry">
        <a href="Praxis.html">
            Praxis/Kontakt
        </a>
    </li>
    <li class="entry">
        <a href="Persoenlich.html">
            Persönlich
        </a>
    </li>
    <li class="entry">
        <a href="Aktuell.html">
            Aktuell
        </a>
    </li>
</ul>

CSS:

#menu {
    height: 32px;
    list-style: none;
    padding: 0;
    margin: 0;
}

#menu .entry {
    float: left;
}

#menu .entry:last-child {
    float: none;
    overflow: hidden;
}

#menu .entry a {
    font-family: Verdana;
    font-size: 14px;
    line-height: 32px;
    height: 32px;
    color: #9d0a6d;
    text-decoration: none;
    padding: 0 10px;
    display: block;
    border: 1px solid black;
}


#menu .entry a:hover {
    color: #6f3f81;
    text-decoration: none;
}

I considered just creating a similar effect by putting them in a nested container with the same background color and centering the element list, but that won't work without additional JS code, because the first and last element have to change color on hover.

Is there a proper CSS solution for this?

Upvotes: 1

Views: 211

Answers (2)

erkinyldz
erkinyldz

Reputation: 688

Well, the easiest solution I can think of is this: Give the first and last "li"

width:15%;

You can play around with the number. This way they will always take the same space no matter whats the width of the screen.

Upvotes: 0

Mabedan
Mabedan

Reputation: 907

The only reliable solution that I know for this one, is display:flex... Give display:flex to the container and flex: 1 0 to the element you want to grow. Make sure to include WebKit and moz prefixes for compatibility. Note that this layout model is rather new and doesn't work on older browsers.

Upvotes: 2

Related Questions