April 16, 2012

CSS On hover dynamically width background image

Question by Roel

I am attempting to create a mouse-over effect on a navigation on my website.
The navigation is a horizontal bar with a few items in it. Code for it below;

<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">About us</a></li>
  <li><a href="#">Our work and portfolio</a></li>
  <li><a href="#">Contact</a></li>
</ul>

This has a plain background color and between every <li> is a border to separate the items. Now I want to give a background image on hover, though my problem is that – as you can see – every <li> has a different width because of its contents and my image for the hover is as below;

hover effect

So it’s actually just a black shadow on the left and right. The right shadow must be placed on the absolute right side of the <li> and the left shadow on the absolute left.

Is there any way to achieve this? Not a problem if it’s with jQuery or anything like that.

Thanks in advance.

Answer by Starx

If you want the shadow, and the variable length effect. Then split the image into three parts. And update your markup to something like this

  1. Left Shadow
  2. Center Part
  3. Right Shadow

Then use the following CSS snippet

li a:hover:before { content: url("image/leftshadow.jpg"); }
li a:hover { background-Image: url("image/center.jpg"); }
li a:hover:after { content: url("image/rightshadow.jpg"); }

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!