31 Jul 2013

Cassette Style Nav Bar That Auto-Fills Available Width

Recently I was trying to make a nav bar that had "pushed-in" buttons (like cassette tape decks), but I was running into a problem. I needed the nav bar to fill the full width, but I couldn't set a background on it because it would mess with the display of the pushed in state. Then I found out that overflow: hidden; does magical things that I can't explain.

Here's the HTML for the above navbar.

1 <ul class="cassette">
2   <li><a href="#" class="cassette-item">Do</a></li>
3   <li><a href="#" class="cassette-item">Cool</a></li>
4   <li><a href="#" class="cassette-item">Things</a></li>
5   <li><a href="#" class="cassette-item">Like</a></li>
6   <li><a href="#" class="cassette-item is-active">This</a></li>
7   <li class="cassette-filler"><span></span></li>
8 </ul>

The trick is to float each list item left, except for the last one. On the last one, you need to set overflow to hidden. Here's all that's required for the magic auto-fill width behaviour.

1 .cassette li {
2   float: left;
3 }
4 
5 .cassette li.cassette-filler {
6   float: none;
7   overflow: hidden;
8 }

Voila! Auto filled width. As for why this works, I have no idea. I learned this magical trick on Stack Overflow.

Here's the whole cassette.scss file, in case you want to copy and use it:

 1 $color: #3498db;
 2 
 3 .cassette {
 4   list-style-type: none;
 5   padding: 0;
 6   margin: 0 0 20px 0;
 7 
 8   li {
 9     float: left;
10 
11     &:first-child > * { border-radius: 2px 0 0 2px; }
12     &:last-child > * { border-radius: 0 2px 2px 0; }
13     &.cassette-filler {
14       float: none;
15       overflow: hidden;
16       padding: 0 3px 3px 0;
17 
18       position: relative;
19       z-index: 2;
20     }
21   }
22 }
23 
24 %cassette-item {
25   $bg: $color;
26   $shadow: darken($color, 10);
27 
28   @include box-shadow(1px 1px 0 $shadow, 2px 2px 0 $shadow, 3px 3px 0 $shadow);
29 
30   display: block;
31   height: 40px;
32   padding: 0 15px;
33   border-left: 1px solid lighten($color, 5);
34   border-right: 1px solid darken($color, 5);
35 
36   background: $color;
37 
38   color: #fff;
39   line-height: 40px;
40 }
41 
42 .cassette-item {
43   @extend %cassette-item;
44 
45   &:hover {
46     background: lighten($color, 10);
47 
48     color: #fff;
49     text-shadow:
50       1px 1px 0 $color,
51       2px 2px 0 $color,
52       3px 3px 0 $color;
53   }
54   &:active, &.is-active {
55     @include box-shadow(1px 1px 0 darken($color, 10));
56     margin: 2px -2px -2px 2px;
57   }
58 }
59 
60 .cassette-filler {
61   span { @extend %cassette-item; }
62 }
comments powered by Disqus