CSS background-position fixed to parent

2019-06-24 00:56发布

my question is a bit tricky and I'm not really sure if it is possible, but I think I have a memory of doing it before or seeing it somewhere. So, I am making a horisontal menu. I have a div block of size 980x36px. It has a background image:

enter image description here

Inside I have links <a href="/">text</a>) which I made block elements (display: block;) and floated left. So now it would look more like this:

enter image description here

Now I want all active links and all links that are mouse-overed to have a different background, like this:

enter image description here

The problem here is that my background image (on hover) is again 980x36 px and is different in the different horisontal positions just like the first background, blue on the left and red on the right:

enter image description here

So, now when I hover on a link I must set the background position some negative horisontal value, for example for the third link I should set something like background-position: -233px 0px; so the colors of the two backgrounds would fit.

My question is how can this be acomplished automaticaly? Here is the tricky part: I don't know the width of all links since they are text and should support multi-language (so they obviously cannot be pre-made images). I don't want to use PNG (I could easily make a semi-transparent 'glass' which would overlay with the first background and create the same effect) - because of.. guess who, yes IE6. And finally I want this to be done with a nice, clean and widely supported technique, so JavaScript is out of the question (I know it's easy, I can make it, I just don't want to use it).

The thing that is familiar in this situation is the background-attachment: fixed; method. In this case it would be great if I could fix the position of the background of each link to the position of the container div. That would be perfect! Just what I need! Each link will be on it's place, but the background would render as if it was on the container div! Well, that's the problem, if anyone knows a good solution.. If not I should consider the less pain, which in my opinion, currently is to try the PNG way with some IE fixer maybe?

2条回答
forever°为你锁心
2楼-- · 2019-06-24 01:48

You should just use a .png as you described in your question.

To fix IE6, you should use one of the many available JavaScript-based .png fixes, such as:

http://www.dillerdesign.com/experiment/DD_belatedPNG/

It's just not worth crippling yourself by pandering to the minuscule percentage of users that are using IE6 and have JavaScript disabled.

(yes, I realise the question is old, and you've probably already created your menu)

查看更多
对你真心纯属浪费
3楼-- · 2019-06-24 01:53

The quickest solution that comes to my mind is using jQuery to position the background accordingly (you can check each element's position and just change its CSS background position).

查看更多
登录 后发表回答