Monthly Archives: October 2011

Vertical Navigation with a Border

I have been working a website with vertical navigation with some transitions and different colors on each item. The menu brought up some interesting CSS issues. I am breaking it down into smaller chunks and tackling each issue in separate posts.

I’m starting with the simplest issue and that is setting up the navigation with a small border on the bottom. The goal is to have the border grow behind the text when the user hovers.

Menu on the right showing the hover state. The border on the bottom grows to show which item user is hovering over.

ul li { 
	list-style: none; 
} 
ul li a { 
	width: 100px; 
	height: 40px; 
	line-height: 53px; 
	border-bottom: 4px solid #999;  
	padding-left: 5px; 
	color: #333; 
	text-decoration: none; 
 	display: block;
} 
ul li a:hover { 
	border-bottom: 35px solid #999;
	height: 9px; 
}	

Explanation

The code is similar to Horizontal Navigation, except you don’t need to float the individual list items, so it is even more simple.

The important part of the code is:
height: 40px;
line-height: 53px;
border-bottom: 4px solid #999;
padding-left: 5px;
display: block;

display: block changes the anchor tag to a block level element allowing you to give it a height. (Normally anchor tags are inline elements with no height.) The full height of the element is 44px. 40px from the height, and 4px from the border.

If I wanted the text centered in it’s box, I could have used a line-height of 40px, which is a standard technique for centering text vertically. However, I wanted the text close to the border. So I set the line-height to 53px and that centers the text on a 53px box, which ultimately places it closer to the border as I wanted. It isn’t the only solution, I could have messed around with marigns/padding, but this seemed the quickest.

The real issue is the hover state.

ul li a:hover { 
	border-bottom: 35px solid #999;
	height: 9px; 
}

I wanted the border to be a full 35px when hovering, so it comes up behind the text. If I didn’t change the height to be smaller, it causes a problem, similar to what I discussed in this post. However, in this case, the outline solution won’t work because I only have a border on the bottom, and outline goes on all 4 sides. See the demo, first column, for a display of the problem.

Changing the height of the box in the hover state fixes the problem. If I want to grow the border to be 35px, I need to make the height 9px, to make sure the total height remains at 44px. 9px + 35px = 44px. In the regular state: 4px + 40px = 44px. The individual numbers are not important. The important part is the TOTAL box height which = height + border + margin + padding. In my case I have no margin or padding.

In my next post, I will show how adding a transition to the border changing caused a problem and how I fixed it.