Rollovers are a nice way to add visual feedback to your website’s buttons. As a visitor moves their mouse over a rollover button, it changes to indicate that it’s clickable.
In the bad old days of HTML, the only way to create a rollover was to use JavaScript to swap the two button images. While this works, it does rely on JavaScript being enabled in the browser. It also adds a fair bit of code bloat to the page, meaning longer download times, and more coding for you.
Thankfully, these days you can create a nice rollover effect using pure CSS; no JavaScript required! Roll your mouse over this button, which is created using just HTML, CSS and a single image:
So how’s it done? Well, it all centres around the :hover
pseudo-class in CSS. Using this pseudo-class, you can style a link both in its normal state and in its hover (rollover) state. By making the link a block element and giving it a background image, we can turn the link into a button. We then simply jiggle the background image around to create the rollover effect.
The button image
The trick to making this type of rollover work smoothly is to have both the normal and rollover images stacked in a single GIF image, with the rollover state below the normal state. Here’s our button image – it’s 107 pixels wide and 46 pixels tall:
On the one hand, this is slightly inconvenient as it means you have to use Photoshop – or a similar image editor – to create a single image containing your normal and rollover images. You can’t just grab normal and rollover button images from somewhere and use them as they are. Of course, this is no problem if you’re creating your site design in Photoshop anyway.
On the other hand, this approach avoids issues with flickering and preloading, which we’ll talk about in more detail at the end of the article. It’s also nice, in a way, to have both the normal image and the rollover image packaged within a single image file; it’s easier to keep track of your button images, and you only have half as many image files to worry about!
The markup
The HTML for our button is wonderfully simple. In fact it’s just a link with an id
, and a span
element wrapped around the link text:
<a id="emailUs" href="#" title="Email Us"><span>Email Us</span></a>
We give the link an ID – in this case, "emailUs"
– which allows us to style the link via our CSS. We also place the actual link text inside a span
element. This means that we can hide the link text with our CSS and display the image instead, yet the link still looks like a regular text link to browsers not using the style sheet – such as a search engine spider or a text-only browser, for example.
The CSS
To turn our regular text link into a rollover button, we apply the following CSS:
#emailUs
{
display: block;
width: 107px;
height: 23px;
background: url("emailUs.gif") no-repeat 0 0;
}
#emailUs:hover
{
background-position: 0 -23px;
}
#emailUs span
{
position: absolute;
top: -999em;
}
First we change our emailUs
link from an inline element to a block element with display:block
. This allows us to give the link a width and height, as well as set our button image as a background. We set the width of the link element to the width of our GIF image, but we set its height to half the height of the GIF; that is, the height of one of the button images. This means that just the top, normal button image appears within the link by default. The bottom, rollover button image is cut off, and therefore remains hidden.
Then we select the link’s :hover
pseudo-class to style our rollover state. This is simply a matter of shifting our background GIF up by 23 pixels, or half the GIF’s height. This hides the normal button image above the top of the link element, and reveals the rollover button image within the link; you can think of it as sliding the GIF upwards within the “window” of the link. When the visitor moves their mouse away from the link again, the button GIF slides back down 23 pixels, returning to its default position, with the normal button image revealed within the link.
Finally, all we need to do is set position: absolute
and top: -999em
on the span
element inside the link. This moves the link text way above the top edge of the browser window, effectively hiding the link text for browsers that support CSS and images.
And that’s all there is to it!
Creating more than one button
If you want to create many rollover buttons in the page – for example, as part of a menu – copy and paste the HTML and CSS, giving each button a unique id
in both the HTML and the CSS and, of course, changing the background image for each button in the CSS.
Alternatively, you could style the link text to be in the centre of your button image, rather than being hidden; you’d then only need one (blank) button image for all the menu options. The tradeoff with this approach is that you lose some control over the look of your button text, and the buttons don’t generally look as nice.
The rationale
You may be wondering why we’ve taken the approach of having both the normal and rollover images within the one GIF image. In fact you could easily rework the CSS to include two separate images, as follows:
#emailUs
{
display: block;
width: 107px;
height: 23px;
background: url("emailUsNormal.gif") no-repeat 0 0;
}
#emailUs:hover
{
background: url("emailUsRollover.gif") no-repeat 0 0;
}
What you’ll find, though, is that the button “flickers” the first time you move the mouse over it, as the browser fetches emailUsRollover.gif
from the server. In other words, most browsers don’t preload the background image of the :hover
state. By combining both our normal and rollover states in a single GIF, we’re forcing the browser to “preload” the rollover state image as it fetches the normal state image.
An alternative approach might be to use a JavaScript preloader, or a hidden img
element in the page, to preload emailUsRollover.gif
, but then we’re kind of losing the point of having a non-JavaScript, pure-CSS rollover!
A nicer alternative is WebCredible’s Trifecta button. This uses an inline img
element in the markup for the normal state, and a background image in the CSS for the rollover state. To create the rollover effect, it toggles the visibility of the inline image. This means that both images are preloaded with the page, avoiding any flickering effects. It also uses markup to display the button text – a technique that we touched on earlier – meaning that you only need one button image pair for a whole menu.
The drawbacks with the Trifecta button are, firstly, that it requires an extra div
wrapped around your link, and secondly, that you end up with an inline image in your markup. Having an inline image means more markup, and also means that you’re fairly committed to having image buttons on your site; it’s harder to replace your image rollovers with pure CSS versions, or with simple text links, later. However, the Trifecta is a nice solution if you like the idea of separate rollover images.
Update 23 Feb 2011: Changed the code to hide the link text using position: absolute
and top: -999em
instead of using display: none
.
A simpler CSS rollover method:
In CSS:
img.hover {display:none;border:0;}
A:hover img.hover {display:inline;}
A:hover img.nohover {display:none;}
In HTML:
<A HREF=”#”>
<img src=”button1.gif” class=”nohover” border=0>
<img src=”button2.gif” class=”hover” border=0>
</A>
[Edited by niente on 03-Sep-09 15:56]
Hey nice approach niente – I hadn’t seen that technique before!
I can’t get it to work at all in IE6, but other browsers (including later IEs) work fine. No flicker either.
I like the simplicity of the CSS, though personally I prefer the cleaner markup of the version in the article.
Always nice to see alternative solutions. Thanks for posting. π
I’m new to CSS so please pardon my lack of experience. I thought this technique would be a nice way to do a true/false trivia button rollover without the hyperlink functionality. Is there something similar to the :hover pseudo-class available for an image without the hyperlink?
If an example of what I’m trying to do helps, see http://indulgedfurries.com/trivia.htm
The buttons don’t need to hyperlink anywhere.
I could link them back to the same page, but that seems sloppy.
Thanks for any input to my steep learning curve!
Hi IFPetMom, and welcome!
You can use :hover on a non-link element (such as a span), with 2 provisos:
1) You need to use a “strict” doctype for it to work in Internet Explorer.
2) It doesn’t work at all in Internet Explorer 6 and earlier.
Example:
If you need it to work in IE6 then you can use a JavaScript onmouseover instead: http://www.elated.com/articles/rollover-buttons-with-javascript/
Hope that helps!
[Edited by matt on 16-Sep-09 22:14]
Matt,
Thanks for the help! I got it working at http://indulgedfurries.com/trivia.htm#trivia
No problem – glad it works! Thanks for the link back. π
Matt
Hello Matt,
This is my first time trying rollover buttons and thanks to your article here I’ve somewhat accomplished it! There’s just one problem… I can’t seem to work out how to make the buttons go along the page in a horizontal fashion. As I add each button they go vertical when I really need them to go across the page.
Any help would be greatly appreciated thank you! π
ByNDii.
Hi ByNDii, welcome to ELATED! π
To make the buttons go across the page, you can use floats. For example, here’s how to create 2 buttons horizontally:
Does that help?
Matt
Ahh I see! Thank you so much π For your article and for your help! It works perfectly π
No worries ByNDii. π Feel free to ask if you have any more questions!
Matt
Hi Matt,
Thank you so much for you advice..I will be using it on a future site.
However it seems that the two images don’t line up vertically…is there a way to fix that.
It can be seen on my staged page here:
http://www.davanticycling.com/pdf_template-includes.html
the two elements contact and payment?
Any insight is most appreciated
Thanks
Amy
Hi Amy, and welcome!
That page looks OK to me – the two buttons are side by side and are correctly vertically aligned. I guess you fixed the problem already…?
Cheers,
Matt
Thank Matt for checking…yes fixed it it was an image issue…sorry for the trouble
Amy
Hi folks,
I am new to the css rollover buttons, but I am working on a project that require them. I have been searching around and have found some great scripts for the menu I require, but need some help customizing it a bit – any help is appreciated.
What I am trying to achieve is online at http://www.oatmealdesign.com/samples/sample_1.jpg
What I have so far learned is at http://www.oatmealdesign.com/samples/index.html
I am not worried about the ragged edges on the JPG image or the line running through the menu – I plan on using a tiling background image for this. What I do need is to add rounded corners to the buttons, and to have an active state for the buttons whereas when the button is pressed and you are on the relevant page, the button will remain dark blue.
I have pasted my html code and css code below. These scripts were gleaned from http://css.maxdesign.com.au.
***************************HTML***************************
<div class=”awesome” id=”banner-2″>
<div class=”nvacontainer_placement” id=”navcontainer”>
<ul id=”navlist”>
<li id=”active”><a href=”#” id=”current”>Profile</a></li>
<li><a href=”#”>People</a></li>
<li><a href=”#”>Expertise</a></li>
<li><a href=”#”>Services</a></li>
<li><a href=”#”>Data Centre</a></li>
<li><a href=”#”>Contact</a></li>
</ul>
</div>
***************************CSS***************************
ul#navlist
{
margin-left: 0;
padding-left: 0;
white-space: nowrap;
}
#navlist li
{
display: inline;
list-style-type: none;
font-family: Arial, Helvetica, sans-serif;
font-size: 13px;
font-weight: normal;
color: #FFF;
}
#navlist a { padding: 5px 20px; }
#navlist a:link, #navlist a:visited
{
color: #fff;
background-color: #707198;
text-decoration: none;
}
#navlist a:hover
{
color: #fff;
background-color: #434054;
text-decoration: none;
}.nvacontainer_placement {
margin-top: 130px;
text-align: center;
margin-right: auto;
margin-left: auto;
}
No problem Amy – glad it works now! Let us know if you need any more help.
Matt
Hi oatmeal, welcome to the forums!
You’ll need to create rounded corners in your graphics package (e.g. Photoshop) and export the images for use as CSS image buttons – for example, see our tutorial: http://www.elated.com/articles/css-rollover-buttons/
To keep a button in its “active” state you can add a CSS class to it and modify the CSS accordingly. For example (this is based on our tutorial):
HTML:
CSS:
If you’re making a whole menu then you’ll probably want to put your links inside an unordered list, as done in your maxdesign example. Let me know if you need help with this.
Hope that helps!
Cheers,
Matt
This tut was a godsend. Thank you
@BigBrotherBiggs: You’re welcome – I’m glad it helped you out. π
Cheers,
Matt
I have a big problem.
I’m setting up a website in Joomla, and it’s made with images as menu. But I can’t make a rollover for the menu image (to change image on rollover).
I have tried several ways, but I wonder if I can code it in the style.css instead?
http://kaptajnb.dk/Kasernerevyen/
While the menu should be the font “Cooper Black” I might experience problems if the font isn’t standard?
How do I do this correctly?
Perhaps your CSS Rollover Buttons might do it for me, but how should this look like, and where should I put it? style.css?
I can easily make the images myself but I’m very new in coding so I’m pretty lost now…
Hi kaptajnb, welcome!
This looks like it will do the trick:
http://www.rtraction.com/blog/devit/easy-rollover-menus-in-joomla.html
(When that page talks about “sprites”, it’s referring to the same technique as used in my CSS Rollover Buttons tutorial.)
Does that help?
Matt
Hi Matt!
Thank you.
What a fantastic quick and nice respond. I’m happy about it. Thanks.
As you can see, I have installed the Extended Menu and I have made “sprites” for all menu images. So far so good.
http://kaptajnb.dk/Kasernerevyen/
Now I need to change my style.css.
Here is my problems right now. How do I make a code for each menu, which are different heights? I know the exact heights for each, so I have to define each of them somehow and afterwards I need to refer to the exact menu image in my css. But how do I make several menu rules in the css, and how do I tell Joomla, that for left_menu_01 I need one rule and for left_menu_02 I need another rule etc?
Can you help me starting out in the right way, please? I don’t need #active_menu, while I have made a normal and a rollover image – 2 images in the same file.
My menu images (from top of my website):
left_01.png: 27 px (height)
left_02.png: 19 px (height)
left_03.png: 30 px (height)
left_04.png: 17 px (height)
left_05.png: 28 px (height)
left_06.png: 24 px (height)
left_07.png: 22 px (height)
left_08.png: 24 px (height)
left_09.png: 19 px (height)
As you see, the height is different on each menu, so I need to define each menu. But how? (I’m very new in coding!)
When you name it “#header ul li a”, does that mean that “a” is the first? Then comes “b” etc? Or does “a” refer to the function of rollover?
How do I name each menu item specificly and how do I tell Joomla to find this exact rule for each menu?
This is what you refered to:
#header ul li {
overflow: hidden;
height: 44px;
float: left;
}
#header ul li a {
display: block;
}
#header ul li a:hover {
margin-top: -44px;
}
#active_menu {
margin-top: -88px;
}
This is how my style.css is now:
/* ######## MENU ########## */
#left UL {
list-style: none;
border: 0px;
margin: 0;
padding: 0;
}
#left LI {
display: block;
}
[Edited by kaptajnb on 08-Oct-09 15:24]
Hi!
I just found something:
<ul id=”left”>
<li><a href=”#” class=”left_01″>Nyheder <span></span></a></li>
<li><a href=”#” class=”left_02″>Billeder <span></span></a></li>
<li><a href=”#” class=”left_03″>Billetter <span></span></a></li>
<li><a href=”#” class=”left_04″>Deltagere <span></span></a></li>
<li><a href=”#” class=”left_05″>Om KaserneRevyen <span></span></a></li>
<li><a href=”#” class=”left_06″>Presse <span></span></a></li>
<li><a href=”#” class=”left_07″>Forestillinger <span></span></a></li>
<li><a href=”#” class=”left_08″>Kontakt <span></span></a></li>
<li><a href=”#” class=”left_09″>Kun for os <span></span></a></li>
</ul>
Should I put this into my index.php and where?
<div id=’left’>
<jdoc:include type=”modules” name=”left” />
</div>
Then put this into my style.css:
#menu .left_01 {
width: 235px;
height: 27px;
background: url(images/left_01.png) no-repeat;
}
#menu .left_01 span {
width: 235px;
height: 27px;
margin-top: -27px;
}
#menu .left_02 {
width: 235px;
height: 19px;
background: url(images/left_02.png) no-repeat;
}
#menu .left_02 span {
width: 235px;
height: 19px;
margin-top: -19px;
}
Etc.
Is this correct?
Hey kaptajnb!
I know nothing about Joomla I’m afraid, so I can’t help there. But essentially it sounds like you’re on the right track. You need to give each menu item ‘a’ element a CSS class (or ID), then add CSS rules for that class/id to create the image background.
Don’t forget to add the :hover rule for each class too (to create the mouseover effect).
Also, you currently have your menu images as ‘img’ tags in your HTML. These should be removed; the CSS should define the images as backgrounds.
You asked: ‘When you name it “#header ul li a”, does that mean that “a” is the first? Then comes “b” etc? Or does “a” refer to the function of rollover?’
That selector means” The ‘a’ element that is the child of the ‘li’ element that is the child of the ‘ul’ element that is the child of the element with an ID of ‘header’. In other words, the link(s) inside the ‘header’ element.
BTW, when posting replies you can use the ‘code’ button (<>) above the text box to wrap ‘code’ tags around your code blocks – makes them easier to read. π
Let me know if you need any more info!
Cheers,
Matt
Hi Matt.
Thank you for your effort.
You are doing a great job.
I don’t think it matters about the Joomla question, while I try to solve the problems in the css instead.
You write: “You need to give each menu item ‘a’ element a CSS class (or ID)”. I don’t understand the “item ‘a’ “…
Is this correct?
style.css
Or should I put the “:” in as you did?
What is “span”, and do I need that? Shouldn’t the” #menu .left_02″ and the “#menu .left_02:hove” do it all?
Is it somehow possible to make you write a bit of my code to make me start right? Then I will finish it and post it here, so you can check it up. π
index.php
Please help me to understand.
[Edited by kaptajnb on 09-Oct-09 00:23]
Hi – great tutorial – thanks!
I have tested on a Mac in Firefox and Opera with no display problems. But, I am creating a vertical graphic navigation list, not horizontal. For some reason I get big gaps between each rollover in Safari (v 3.0.4). I even tried cutting the graphics to a vertical layout, but the same problem persists. I have no problem with vertical nav (display: inline;) – just this one. And I haven’t even tried IE yet…
Any ideas are greatly appreciated!
– shorescores
THE HTML
THE CSS
@kaptajnb:
The spans are there for your backup HTML text versions of the menu buttons (for accessibility/SEO). They should be set to ‘display: none’ in your CSS (as shown in my original article):
Do not write ‘:span’. The ‘:’ is only for pseudo-classes (such as ‘:hover’).
Here’s a complete CSS example for one of your buttons:
This assumes the following markup (note that your UL element should have an ID of “menu” in this case, not “left”):
Does that make sense? π
Matt
@shorescores:
Welcome to Elated!
By “vertical”, you mean one button below the other, right?
This works for me in FF 3.5 Mac, Safari 3 Mac, IE8 Win, with no vertical space between the buttons:
Markup:
CSS:
Hope that helps!
Matt
Matt – you are too kind! I have been cursing at the discrepancies between browsers for the last few LATE nights π
For my own understanding, it looks as if my and your HTML in the list are the same. Moving on to the CSS, I had:
But, you have
So, unless I am missing anything else, it seems critical to make sure the li item is displayed as block, using 0 for the font-size and line-height.
You are too cool. Now I know why they call this site, “ELATED”!
Huge thanks!
– shorescores
@shorescores: You’re welcome – happy to help. π
Actually I don’t think the ‘display: block’ on the LI is probably necessary, since these display as blocks by default anyway. It can’t hurt though.
The key things are:
1. Removing the float, so that the buttons appear one beneath the other, and
2. Using zero font-size and line-height to remove vertical space in IE.
Browsers can be very frustrating sometimes can’t they! π
Cheers,
Matt
Matt – yeah, I think I had the floats in there, for a previous inline horizontal navigation. This is not good for a vertical layout. I will note zero font and line-height from now on!
Thanks
– shorescores
Hi Matt.
I have – for a start – made my website using no sprites. I will later om change this, when I am more experienced. So I solved the problems with roll over images:
http://kaptajnb.dk/Kasernerevyen/
Well at least I thought I did… I just saw my website on a PC with IE and the menu images for the text isn’t showed! Only top menu “NYHEDER” is there. The menu links does work fine though. Top right there is a menu image as well, and this is also fine in Safari and Firefox but not in IE. Nothing is shown here either for IE!
Any suggestions?
index.php:
style.css:
Hi KaptajnB,
The IE problem is caused by not having a space between the ‘)’ and ‘no-repeat’ in your ‘background’ properties. For example:
should be:
You should always have a space after the ‘)’. You should also have space between a property name and its value:
On a more general note, I’d recommend cleaning up your markup as it currently has a few errors which could cause problems in various browsers:
http://validator.w3.org/check?uri=http%3A%2F%2Fkaptajnb.dk%2FKasernerevyen%2F&charset=%28detect+automatically%29&doctype=Inline&group=0&user-agent=W3C_Validator%2F1.654
BTW your rollovers suffer from the problem of not appearing for a second or two when you mouseover them, because the browser hasn’t yet fetched the rollover image. (This is why sprites are a good idea!)
Hope that helps π
Matt
Dear Matt.
Thank you so much. Great help!
You wouldn’t happen to be a champ in putting in flexcroll scrollbars as well?
It is a javascript, and though I have tried to follow the instructions, I can’t make it work out correctly. I get normal scrollbars, when I try (so I have removed them again).
http://www.hesido.com/web.php?page=customscrollbar
Where do I exactly have to put the codes?
If you have no idea, just forget it. π
Thanks again.
As far as I can tell, you need to upload the flexcroll.js JavaScript file to your site then link to it in your page’s HEAD section:
Then create the CSS for the DIV that you want to have the custom scrollbars:
Then it’s just a case of adding the DIV to your markup:
(Not that I’ve tried it, but it sounds like it should work!)
Cheers,
Matt
Hi Matt.
Thanks again.
I can’t solve it though.
I did put this into my index.php:
I tried to put the exact code into, but it didn’t do anything, so I figured out, I had to put the class to the content div instead.
Therefore I made the adjustments to my content in style.css:
Also I put the JavaScript in the Header and the flexcroll.js file into my site (same place as my index.php. I have tried to upload it to same place as my style.css, but this don’t change anything.
I do get the scrollbars, but it is normal scrolbars. I put the flexcroll.js file for minimal scrollbars, so this showing up is the wrong one.
Could it be some kind of conflict with Joomla or other things?
I know it is possible, because it is done here:
http://arcteam.de/index.php?option=com_content&view=article&id=74&Itemid=56
There is a different way to do it here, but I don’t know how this should be done:
http://www.solutoire.com/experiments/scrollbar/index.html
Any suggestions?
Hi KaptajnB,
You haven’t uploaded the JavaScript file (or you’ve uploaded it to the wrong place):
http://kaptajnb.dk/Kasernerevyen/flexcroll.js
—
Not Found
The requested URL /Kasernerevyen/flexcroll.js was not found on this server.
—
Matt
Hi Matt.
I have uploaded it to the template folder, where my Joomla template is located. Please see attached.
It might be a structure problem with Joomla?
Now it is uploaded where you asked me to…The text disapear while it is here. I might change it again.
Strange that it works out fine here:
http://arcteam.de/index.php?option=com_content&>;view=article&id=74&Itemid=56
Hey KaptajnB,
Yes I see the disappearing text too. Or rather, disappearing images – I’m on this page:
http://kaptajnb.dk/Kasernerevyen/index.php?option=com_content&view=article&id=2&Itemid=3#
Could be a Joomla thing – I don’t know. You do have a huge amount of JS included inside your ‘content’ div (mootools etc) that might be conflicting – these should probably be placed in the page HEAD section.
Maybe you could try the scrollbars script with a very simple HTML page, then once that’s working, try to get it working in your Joomla pages?
Cheers,
Matt
I read that the Mootools is placed in Joomla 1.5 as standard. I don’t know why, because of my poor experience in codes and Joomla. I really don’t know the possible function of mootools. Do you?
Maybe there is an easier way to make the scrollbars?
/Morten B
MooTools is a JavaScript framework used by many other scripts. There’s no problem in using MooTools as such, but it’s a very big library and you have included it right inside your ‘content’ div. I would move it into the HEAD section of your page.
As I say, the best approach would be to try and get your “flexcroll” scrollbars working on a very simple HTML page. If you can get that working then you know that, in principle, it will work. Then it’s just a case of working out why it isn’t working in your actual site.
Cheers,
Matt
Matt,
Your CSS Rollover Button example is great. I like that you have text for the search engines to see but what about if the user has images turned off?
Search Engine crawlers ARE users with images turned off.
@LisaA: Welcome to the forums!
You raise a very good point. If you use a CSS-enabled browser and turn images off then you will see nothing at all. The bad news is that I don’t think there’s any way round the problem – for example, see:
http://www.alistapart.com/articles/sprites
“In the rare cases in which users have turned off images in their browsers but retained CSS, a big empty hole will appear in the page where we expect our images to be placed. The links are still there and clickable, but nothing visually appears. At press time, there was no known way around this.”
Also see http://www.hicksdesign.co.uk/journal/image-rollovers-with-css which mentions a possible solution on another blog (which unfortunately is down at the time of writing).
The good news is that hardly anyone browses with no images these days, and those that do are usually using text-only browsers such as Lynx, which don’t support CSS either. Hence they will see the text link.
Cheers,
Matt
Great article. Created test css/html pg. with several img buttons and it worked as shown. I don’t understand the “href=# ” in the anchor. How can you click on the image and have it go to another file?
thanks
Hi scurveedog, and welcome!
The “#” is just an empty anchor for the demo, so that clicking the button doesn’t jump to a new page. To create an actual link, just replace the “#” with the URL of your destination page:
Hope that helps!
Cheers,
Matt
Matt, thanks for the quick reply! I’m new to html/css and your site is a godsend
You’re welcome, scurveedog! π If you have any other questions please feel free to ask.
Cheers,
Matt
Great little tutorial, thanks. Am learning the switch from html/javascript to css and these things help so much. I have a question about the URL before the name of the image file rather than the old way of putting the path or a relative directory. Does that mean the image will be found in the root directory of the current URL or in any directory of the URL? Howzitwork?
Thanks again.
Hey moonliner, welcome to ELATED!
You can use absolute or relative URLs in CSS, just as you can in HTML:
One thing to note when using relative URLs (the 2nd and 3rd example above) is that the URL is relative to the location of the CSS file, not the Web page.
Here’s the full spec:
http://www.w3.org/TR/CSS1/#url
Hope that helps! Let me know if you have any more questions.
Cheers,
Matt
Thanks Matt,
“the URL is relative to the location of the CSS file” is the biggie.
That’s why I couldn’t get things working. Now I understand!.
Cheers,
Douglas
No problem Douglas. That’s caught me out a few times too. π
Matt
I’d like to add my voice to the chorus of grateful visitors.
While there are many articles concerning this technique,
you make it particularly clear by explaining the logic of the workflow.
Thank you very much indeed.
Igor Borodin
Thanks for your kind words Igor – much appreciated. π
Matt
THANK YOU, first of all! π Ok, so on to my question! I have my rollover button menu set up horizontally, lookin’ all pretty and whatnot. Is there a way to code it so that the rollover stays in the hover state to indicate which page the viewer is on? For example, the buttons in my menu switch from white to green upon rollover. When the viewer clicks on the “contact us” button and goes to the contact us page, I’d like the contact us button to stay in the green (hover) state.
@designerchica: Welcome to ELATED. π See my post earlier in this topic (dated 02-Oct-09 22:13) – this shows you how to keep a button highlighted.
Cheers,
Matt
Hey matt,
I would just like to say thank you very much for another great article.
cheers , π
@aussieboy_86: You’re welcome! Thanks for your comment. π
hey matt,
im having a problem with my images not showing up. the links work and the clicking area butt theres no image. any idea whats going on?
Hey thetrakis for some reason i got your email? anyway i had the same problem and my images were not in the same directory as the html page. Hope this helps.
Hey aussieboy_86,
You probably got the email because you’re subscribed to the topic. If you want to stop getting the notify emails for a topic, you can click the “unsubscribe” link in the email, or un-check the “Email me any replies to this topic” checkbox in the topic page.
Anyway, thanks for answering the question. π
@thetrakis: This tutorial might also help – see “Common mistakes when using HTML images” towards the end:
http://www.elated.com/articles/html-images/
Cheers,
Matt
No problems , i don’t think you can ever stop learning so it’s good to see what problems people encounter .
@aussieboy_86: My thoughts exactly. π
Hey Matt I like this technique for making rollover buttons but I want to use it in a horizontal menu. When I create multiple buttons they stack ontop of each other. I guess this is the display:block as display:inline works but then you cant set the height. How would you go about creating a horizontal menu with this css?
hello matt,
today i founded your tutorial and it is very good, mostly because it is very, very simple.
i have a question for you. i am doing some site redesign and it is still in progress. you can see it on http://www.rp.rs/test/nalepnica-za-mesnu-industriju.html
i used your tutorial in lower right corner, in vertical navigation with small pictures. left from those buttons is background image in parent DIV tag.
is it possible on one click on button to change image in parent DIV tag, without using javascript?
ps. i am sorry for my tarzan english
@darshi: Welcome to the Forums! See my post earlier in the topic (dated 26-Sep-09 09:41) for how to lay out the buttons horizontally.
@DavidOdSrbije: Welcome also! Sadly CSS doesn’t have an “onclick” pseudo-class, although you can sort of hack it together – see http://bonrouge.com/br.php?page=cssonclickswitch for an example. Personally though I would just use JavaScript (http://bonrouge.com/br.php?page=imageswitch). If you wanted to avoid JavaScript, you could place the left-hand image in an iframe and use the “target” attribute in each of your button links to load a new image into the iframe when each button is clicked. (BTW I like your page graphics!)
Cheers,
Matt
well, i will do it in old, html way. i will make as many pages as i need and link them to buttons. if i have 10 pictures, i will make 10 pages. pages are similar, with only one difference, the picture.
thank you, matt
@DavidOdSrbije: Sounds like a good plan. Good luck, and if you need any more help feel free to ask in these forums!
Cheers,
Matt
Hi there,
This might a be a silly question, but here it goes…
How do I add functionality to these buttons?
Do I use a hotspot?
Please advise…
Hi suzyq_ and welcome to ELATED!
To turn the button into a link, simply replace the “#” in the href with the URL you want to link to – for example:
Does that help?
Hi there. I like your solution to CSS Rollover buttons, but it seems to require a different image for each nav button. I’ve been trying to create a vertical nav bar with CSS rollover buttons that change the position of the background when hovered over. I wanted to use a single image for all of the buttons and style the text in the link using CSS, but cannot get the text to appear in the right place. I’d really like it to be centred vertically over my background image. I’m sure I’m missing something fairly obvious, so I’d be grateful for your input. I’ve put it online at http://www.ourotherwebsite.co.uk/CSS_test/test1.html
Thanks for your help.
The html is:
And the CSS is:
[Edited by matt on 04-Feb-10 01:19]
Hi Chalky, welcome to ELATED. π
The best way to centre the text vertically is to use the “display: table-cell” property:
Sadly this isn’t supported by IE6 or IE7, although IE8 supports it fine.
The next best thing is to use padding to centre the text as closely as you can, eg:
You might need to experiment with different padding values until you get something that looks centred on most browsers.
Or you might be able to get something like this to work with your buttons: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
Hope that helps!
Matt
Hey Matt, great article – just what I’ve been looking for/
I have a small problem though – after altering the code and placing it in Microsoft Web Expression (3) the button shows up in the application but refuses to be displayed when previewed in any browser.
The real kicker is that the button is actually there – if you can find it you can click on it and follow the link, but it is essentially invisible which isn’t much help (so I have yet to test its hover functionality).
I’m probably doing something completely wrong so any help would be greatly appreciated – I’ve included the code below…
[Edited by matt on 04-Feb-10 01:21]
Hi Marky, and welcome. π
I’m guessing it’s because your CSS references the background image file using an absolute URL that points to the file on your hard drive:
This should instead be something like:
(assuming you put all your images in an “images” folder at the top level of your site).
If you can post the URL of your page on the web then I can take a look and hopefully pinpoint the problem.
Cheers,
Matt
I’m a complete novice at css (& html), but I thought the best way to learn is to just do it, so I’m trying to follow your tut, but the image doesn’t show on the page and all the css text is actually visible, to be honest I don’t really know where to put the css code but my code so far is:
Can you please advise me on where I’m going wrong? Thanks in advance. I forgot to add; the image is in the same folder as the webpage, and I haven’t uploaded it to a server or anything.
[Edited by sycomadness on 15-Feb-10 10:57]
@sycomadness: Welcome to ELATED. π
You need to put your CSS inside <style> tags, as follows:
Hope that helps!
Matt
Thanks – got it working.
Can I ask though, what does <style type=”text/css”> actually mean? Also would it be possible to keep the css in a seperate file?
The HTML ‘style’ element lets you embed CSS styles within the ‘head’ element of an HTML document.
Yes, you can keep the CSS in a separate file instead – in fact this is generally the best approach. If your file is called, say, style.css then you’d link to it from within your page as follows:
Cheers,
Matt
Right. I’ve (finally) got the site uploaded and I took your advice about the absolute URLs and changed them (also making sure that when i uploaded the files, the images folder was at the top level of the site)
Unfortunately I still have the exact same problem as before where the like still works despite the images being completely invisible… At least now the site is up though and can be viewed at http://www.reonsigns.co.nz
Any suggestions on how to make these buttons show up?? Thanks for your help π
@Marky: You’re using backslashes for folder separators in your CSS:
You need to use regular slashes instead:
Cheers,
Matt
Hahaha wow. I thought it might be a simple solution – thanks so much! It works like a charm now π
Absolutely brilliant. You’re the man Matt π
– A very happy Marky Sharky
Glad you got it working Marky – the end result looks good too π
Cheers,
Matt
Got it all working so I tried to experiment abit and so far I’ve only failed.
I’m trying to add a third image, for when the button is clicked. Made a file with 3 buttons stacked and used the following code:
All I’m getting is a static image (the third one). Any ideas?
@sycomadness: I can’t see any problems from looking at the code. Could you upload your page and post the URL so we can take a look?
Cheers,
Matt
Wasn’t working and just signed up to free server hosting (x10) and was waiting for the confirmation email to arrive, so decided to check it out one more time and for some reason its started to work now. Haven’t made any changes to it so don’t know what the problem was before.
Hi,
I’ve used this method for the buttons for this site: http://www.barbaraburtonphotography.co.uk as I wanted complete control over how they looked for the font etc and I think the text always looks nicer like that anyway.
They’re working fine but because I always use a static 3rd image to show what the current page is, I’ve had to make a separate style sheet for each page to specify that the image on the button for that current page should not move when hovered over.
So for the home page the css for the home button is:
#home {
display:block;
width:103px;
height:24px;
position:relative;
float:left;
background-image:url(media/homebutton.jpg);
background-position:0 -48px;
border:none }
(and in the html I just removed the link)
whereas the css for the other buttons have the hover and span parts like this:
#weddings {
display:block;
width:134px;
height:24px;
position:relative;
float:left;
background-image:url(media/weddingsbutton.jpg);
border:none }
#weddings:hover {
background-position:0 -24px }
#weddings span {
display:none }
and that has to be switched round for each individual style sheet. So I guess my question is, is there a way of doing all that on only one style sheet to make things simpler? I tried giving all the links the same class id and removing they’re individual ids in the html, with the thought that I could then give the current page an active class id, but then all my links just disappear like this: http://www.barbaraburtonphotography.co.uk/test.html.
And the only other thing I noticed is that giving each link a separate id in the html also stops the page from validating (w3c validation service flags it as an issue anyway). But yeah I think I’ve just completely confused myself and am probably over complicating things as usual, so any suggestions would be appreciated.
Thanks!
@freakanonymous
You can have multiple elements with the same class on a page, but not with the same id on a page.
eg.
is OK, but
is not valid.
Does that help?
Hi! This is really nice and it works in my menu, but the links appear in a block while my menu is horizontal. Is there any way to make the rollovers inline?
Hi Cristiana, welcome to the forums!
See http://www.elated.com/forums/topic/4685/#post18069 , which I think will answer your question.
Cheers,
Matt
Hello
Thanks for this tutorial, as a Web Design student it was very useful, something they didn’t teach me at uni.
However, I have a problem. I am adding drop down lists into the mix, so that when I hover over a menu item, a list drops out from under it. When I move my mouse onto the drop down list, the menu item moves back into its original position.
Here is the site so you can see what I mean, just move your mouse along the turquoise bar below the logo, and then down into the menu list:
http://numyspace.co.uk/~unn_l203081/Project/Plugged_In.html
Any way that I can keep the menu item position changed as if I was still hovering over it?
Thanks
Mike
Nevermind, after countless hours of torture, I figured it out. Slightly different code to what is used for normal CSS Rollover’s, so I will list it here in case some other poor sod has the same issue one day π
#menubar a.home {
display: block;
width: 164px;
height: 45px;
background: url(“images/home_hover.gif”) no-repeat 0 0;
}
#menubar :hover a.home { << this “a.home” is the key!
background-position: 0 -45px;
}
Thanks again for this tutorial
Mike
[Edited by mykkenny on 08-Apr-10 16:23]
Hi There
Thanks for the great tut!
I am using this in a menubar that is called into each page by PHP.
I would like to have an active state for buttons that are clicked –
However this means that I can’t have an active state class that is specific to each page. (The idea being that I have a standalone menubar that works in each page.)
Is there any way round this? For example a class that is triggered by some code on each page? (effectively turning a class on and off??)
Cheers!
David
yo hi there…nc tut…
helloΓ’β¬Β¦I am kind of a newbie with css and yes I do understand and succesfully made that single rollover but I want to have multiple image rollovers in one page and these multiple image rollovers should be connected or should i say side by side to conserve space so how can I do that? pls. do reply and thanks in advance! I want it to be connected left to right. It’s also not intended for a menu they are just images with rollovers which I would like to link to separate links. pls. do reply thanks.
@davidmoodie: It’s a bit hard to work out what you mean – can you post a URL of your page perhaps?
@bk_rik: Float the buttons left, eg:
Matt,
I was successful at creating a horizontal menu navigation. I am having trouble with the background image and navigation bar. I am wanting to place the nav bar in a specific location on top of the back ground image. Here is the code I’m working with.
Thanks Matt
@jcwbu38: I’m not sure exactly what you’re trying to achieve here. Which background image are you referring to – http://img192.imageshack.us/img192/5712/telioswelcome.jpg ? Why does that image also contain the menu?
BTW you could create your rollovers using pure CSS – no images (such as http://img263.imageshack.us/img263/752/contactnav.gif) required. Just use text for the links, set the links to “display: block” and add some padding. Then change the background colour to blue using :hover. Much easier, and it’ll speed up the page load too. π
Matt,
I created a mock up of the site with the navigation bar all as an image. What I am wanting to do is to remove the navigation bar in my image and insert a real navigation bar with the CSS code I’ve learned in this form.
I usually create unique div ids for each image and put an absolute positioning parameter on it so I can place it where I like on the page. I am wanting to put the navigation bar that I created above into a div and position that over my background image. I’m having trouble with this though.
Does that make more sense?
@jcwbu38: I still don’t understand whether you’re planning to overlay your menu on top of the existing menu in that image (http://img192.imageshack.us/img192/5712/telioswelcome.jpg), or whether that image is just a mockup. But leaving that aside… π
If you want to absolutely position each rollover then just use position: absolute along with the left and top properties – for example:
Does that help?
Tried the code on the html page and it works fine in Firefox and IE7, move it to remote css sheet and it works in IE7 and fails in Firefox. Any suggestions?
Love the idea.
It also works great using the top, center or bottom alignment as well…center being if you want to have a hover and active state in the image.
Heres what Ive been using for my rollovers (well, one form of it)
.home A:link {display:block; width:100px; height:25px; background: url(home.png) top;}
.home A:visited {display:block; width:100px; height:25px; background: url(home.png) top;}
.home A:hover {display:block; width:100px; height:25px; background: url(home.png) center;}
.home A:active {display:block; width:100px; height:25px; background: url(home.png) bottom;}
Heres an example of a 3 state image and the code above.
http://web77.org/codework/916-floatingsidemenu/
Works in every browser that Ive tried so far.
Thanks again for the idea
π
“Hi! This is really nice and it works in my menu, but the links appear in a block while my menu is horizontal. Is there any way to make the rollovers inline?
======================================
I use positioning myself
Heres an example…
http://web77.org/codework/902-website/
<div style=”position:relative; width:500px; height:101px; left:50%; margin-left: -250px; margin-top:10px;”>
<div style=”position:absolute; top:0px; left:0px;” class=”nav1″><a href=”index.shtml”>Home</a></div>
<div style=”position:absolute; top:0px; left:100px;” class=”nav1″><a href=”contact.shtml”>Contact</a></div>
<div style=”position:absolute; top:0px; left:200px;” class=”nav1″><a href=”aboutus.shtml”>About Us</a></div>
<div style=”position:absolute; top:0px; left:300px;” class=”nav1″><a href=”community.shtml”>Community</a></div>
<div style=”position:absolute; top:0px; left:400px;” class=”nav1″><a href=”links.shtml”>Links</a></div>
</div>
@WmTipton: Thanks for your suggestions. Love that page background photo. π
After trying 3 different tutorials, yours is the only one that worked. Thanks for the clear, concise instructions!
I had a question though.
If I want to build an image portfolio with lots of little CSS-styled rollovers, what do you think is the best way to organize them all? In a Div tag, in a UL list?
Also, what would the code look like if one were to do this?
Thanks again,
Asterion
@asterion: I would probably use a ul list, and float each li left so that the thumbnails flow across and down the page.
Hello.
I have installed this phpBB3 style on my forum.
http://www.awesomestyles.com/phpbb3-styles/demo/macinscott-3?l=en&version=
But it doesn’t have rollover buttons. So I found your great article and I would like to change the buttons into rollover.
I have already the necessary “double” images, but I have no idea where to write the CSS and HTML codes you provide.
Should I paste this code
into the file “stylesheet.css”?
Also, the code
where should I paste it?
Into which html file, and where? At the end of the file, at the beginning?
Sorry, but I have no previous experience in CSS and HTML, but rollover buttons is something that I want to have in my forum.
Thank you very much.
[Edited by nikosda on 29-Jul-10 02:38]
@nikosda: I’m not familiar with the theme, but yes, if stylesheet.css holds the theme’s CSS then you should probably place the CSS rules in there.
You’ll need to paste the ‘a’ tags wherever you want to have the rollover effects in the theme. That depends on what buttons you want to apply the rollover effect to, and the file(s) where the markup for those buttons are stored.
Great, very useful. Thanks alot. This is by far the simplest solution I have across.
[Edited by repowell on 02-Aug-10 13:00]
@repowell: You’re welcome. Thanks for the feedback!
Thanks for the tutorial. Really clear and easy to put into practice however, I was wondering if anyone knew if there would be a reason that this would not work when used in a div placed in the regular HTML section of a php form page? I am very new to this and would appreciate someone telling me if there’s a simple rule that states why it is not possible?
I would be happy to post code but it’s really quite long. The form works and everything else is great – just the rollover doesn’t want to play ball. It won’t even act as a link…
Please, if you have any helpful ideas let me know.
Thank you.
Hello Matt Doyle…
Thanks for this excellent tutorial. I have made use of it already on my home page at http://www.sampasystems.com and you made it very simple for beginners like myself. You do nice work!
Best regards from Gilberto in the Dominican Republic
[Edited by gilberto on 05-Aug-10 17:55]
@Scottland75: Hmm, something may be clashing in either your markup or CSS. Can you post a link to the page online please, so we can take a look at the source?
@gilberto: Thanks for your kind words! I’m glad you found the tutorial helpful. π
Matt
I figure it’s probably something ridiculously simple. Unfortunately, I don’t have it up on a live site yet or even a test site so without pasting the code onto this page or sending the php file I’m not sure how to get it to you. Please excuse my ignorance. This is the first forum I’ve ever posted on. How should proceed?
Thanks
Good morning Scotland75…
Thanks for your kind offer and yes, please send me a note at mcwhirtergil@gmail.com and I will be able to communicate directly.
@Scottland75: It will be easiest for us if you can paste the HTML output from your script (ie the web page) into a text editor and upload it somewhere. If you also upload the images then we can easily see where it’s not working.
Failing that, you can paste the HTML here in this topic (make sure you use the <> code button to wrap code markers around your code).
If you are using more than one rollover in a style sheet, you can make it somewhat dynamic by using relative background positioning to save css code.
i added the relative positioning to fix when a parent div uses absolute positioning.
[Edited by syruf on 20-Aug-10 17:03]
I’m struggling a bit with making this work in a horizontal menu. My css looks like this:
and the html like this:
Problem is that the first two buttons (home and about) line up and space perfectly. Everything after that lines up incorrectly. See example here: http://www.namuvo.com/lab/css_hover/menu.html
Inserting a “top” value doesn’t make any difference. The buttons remain staggered.
The final html will be in a table that centers on the page. Any help would be greatly appreciated.
[Edited by uvo_design on 31-Aug-10 15:43]
Hi uvo π
Its probably not relevant, but I used a different approach to positioning the buttons so I could manipulate them easier individually (if needed)
Of course, my coding is a bit different to begin with (to avoid some issues I was having with IE).
Heres a couple examples;
http://web77.org/codework/912-gearbuttons333/
http://web77.org/codework/913-heartbuttons/
And heres the code to position each button within an HTML Div…pretty straightforward…
….heres what I have for each button…
[Edited by WmTipton on 31-Aug-10 17:18]
@ WmTipton
Thanks for the reply. I actually ended up getting it working by playing around with different tags and I ended up managing (at around 2am…) π
Here’s what i did in case anyone’s interested:
…etc…
and the html:
Sample can be viewed here: http://sitebuilder.yola.com/sites/D79d/D448/Ddfe/D238/U8a4986ca1f69c211011f832efd844d97/8a4986cb1f69c1e3011f833bbf9d25e7/specials.php?sys_preview
@uvo_design: Glad you got it working – the end result looks really good. π
Matt
Hi, Thanks for this. I would like to put the buttons I have made using this CSS into my WordPress blog. If anyone can help me with that thanks very much!
@newyorker: If you want to put them into your WP theme then just add the markup to your theme .php files as appropriate (wordpress/wp-content/themes/theme_name). Add the CSS to the style.css file in the same folder.
Hi, Thanks Matt. OK, problem here. Please excuse my ignorance as I’m new at CSS and WordPress. I’m trying, for starters, make just one rollover with a single image in WordPress (self-hosted). I created a new theme (composed of two files, index.php and style.css) in WordPress (I don’t necessarily want to end up creating a new theme but it seemed like a simpler way to try this, instead of changing a more complex premade theme).
My style.css file has this code, from your tutorial–my div id is “navlist”:
I uploaded style.css to the server’s theme file. The theme name is “basic.”
Then I went to WordPress, clicked on Add Page and then on HTML. I typed this HTML into the page:
When I preview the page I don’t see anything at all.
I didn’t change the index.php file and wouldn’t know what to put in it. The entire php file (which is the default) reads:
As I said, I get a blank screen. Can you tell me how to get this rollover to work in WordPress? (I haven’t tried it outside of WordPress).
Thanks very much!
Puzzled
@newyorker: That index.php won’t do anything apart from put the blog name in your browser’s title bar. What’s the URL of the page?
Also, please create a new topic as this more about WordPress, and isn’t related to the original article:
http://www.elated.com/forums/authoring-and-programming/topic/new/
Hi, me again…
I wasn’t sure how to to a whole page of this type of CSS rollover, and I looked at Trifecta , but I wanted my text to be part of the image. So I found a tutorial on
http://inobscuro.com/tutorials/image-rollover-menu-19/
that seemed a good way to do it. It tells you to put the alt text at -1000 so it’s off the screen. Seemed to work great, but the problem is that in one of the rollover sections, some of my text is visible on the left side of the screen. Here it is (named the page after the tutorial):
cbig-nyc.com/obscuronew.html
Whether I type in -100 or -2000 the text shows the same.
So, I tried going back to the home page o of the site I’m trying to redesign, which was done using Javascript.
cbig-nyc.com
I tried taking out the CSS rollovers and pasting all the Javascript into the HTML page. The images showed up and the rollovers worked, but the formatting was lost. I tried creating a new div for the menu and writing 0 for margins and padding but that did no good. I’m unsure how to sort out the mess of the CSS that’s in the original page and the new CSS in my page. I’d like to use the Obscuro if there’s any way it could work (wrote to the site, no response yet).
If nothing else works I will try to redo it all as sprites but may have to bug you about formatting them. In your opinion what would be the best way to do this? Is there some way to easily insert the Javascript with the images fitting my layout? I’m new at this and have just been following tutorials. I haven’t even tried to make a WordPress theme yet…
Thanks again,
Vicky
@newyorker: That page looks OK to me (Firefox 4.0b6 Mac).
I would nearly always recommend CSS sprites over JavaScript for rollovers these days.
Please post questions in a new topic unless they are specifically about the original tutorial:
http://www.elated.com/forums/authoring-and-programming/topic/new/
using this css rollover button technique works great, but how do i get them spaced evenly across top of page or centered across top of page horizontal? when i use float: left in my css, they all go left naturally, but i want them spaced across the top. any advice would be greatful. thanks.
@duncan79: You’re asking a general CSS layout question. Please start a new topic:
http://www.elated.com/forums/authoring-and-programming/topic/new/
Sup Matt
First off, you’re an effin CSS genius. I thought hovers only applied to A elements. PROVED ME WRONG HA!
Secondly, I’ve been jiving around with style of rollover since you first created the tutorial so I’m pretty stoked I get to use it in real life for a legitimate product.
Now for my question, I have already read that you can keep the image in an active hovered state after you roll off of it, however.com, do I have to do it with an unordered list vertically or can I maintain what I have right now which is horizontal?
Second question, from your suggestions from the 02 Oct 2009 discussion, when would your actively hovered image go back to a non-hovered state?
Great help thank you! Really easy to follow π
@cwalkdawg: Glad you found it useful. π However I don’t think that you can keep an element in a hovered state when the mouse has moved away from it (without using JavaScript).
@impelmedia: Thanks for the feedback π
I’m doing my first site design completely/strictly using CSS only…This was wonderful help, I’m so pleased!…Can’t believe I did it, well, with your great help!
Thanks so much for posting this…I found it quite easy to follow.
@jazzie2000: That’s great to hear! Thanks for posting your comment. π
This is a nice, neat trick well explained – but it doesn’t appear to work in IE or Firefox.
In both these browser windows I see nothing at all where my buttons should be – safari is fine.
beelzebomb – – Not sure what the issue is, but it views perfectly in IE 6,7,8, Firefox and others for me…Maybe it’s the doctype that you are using that is the problem…
Thanks Matt and uvo_design!
I’ve gotten the buttons to work horizontally, but I’m having trouble centering them (http://philipos.com).
Here’s my html
and the css…
…etc…
Much appreciated!!
Philip
Hi jazzie200, I also had weird issue with a .png file not showing on firefox/ie as well – I wonder if it’s down to using png rather than jpg?
The html/css all validates well enough.
@psolomon: Looks OK to me – I guess you fixed it?
@beelzebomb: Very strange – possibly a problem with your browsers or OS. Can you try on a different machine? Also try clearing your browser caches etc.
Matt, I tried on 3 machines; macbook running safari & firefox, my g5 running safari & opera & my old windows pc running IE7 – all was fine on safari, but not on anything else.
I had to get the site I was working on up, so changed the code to a standard 2 pic option which works along with changing all the .png files to .jpg files.
When I have time I will go back & do some testing using .jpg files only – I hope that was the issue cos I like this idea!
very new to coding… however, this tutorial was very easy to follow and started working much better once i realized that i needed to wrap the code in <style> tags (like i said, very new to coding).
the problem i am getting is:
the whole image is being shown (not just the top half) until i roll over it. when you roll-over, the bottom half “moves up” and the top “dissapears”. however, i am not sure how to just make “the top half” show until you roll over.
————
the code at the top:
—————
and the inline code:
—————
can be seen live at: http://cedarlee.org/shopping-map_3.html
i’m sure it’s something simple, i just don’t know what i’m doing (but i’m trying)…
thanks.
I’ve just replicated your code & it worked ok with the <style> tags removed.
Can’t see all your files of course, but in case it helps, I separate my css & html into two text files (for example: ‘index.html’ & ‘buttontest.css’)
Then link the css file to the html file, so that the style attributes affect what is in the html, & consequently what you see when the site opens up.
If you recreate these 2 text files, put them in a folder on your desktop so everything is constrained along with the jpg file (change the background link to just “facebook_button.jpg”)
Click on the html file & it should open ok.
Here’s the code I used:
IN THE HTML FILE: –
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″ />
<title>button test</title>
<link rel=”stylesheet” type=”text/css” href=”buttontest.css” />
<a id=”facebook” href=”#” title=”facebook”><span>facebook</span></a>
& IN THE CSS FILE:-
#facebook
{
display: block;
width: 134px;
height: 26px;
background: url(“facebook_button.jpg”) no-repeat 0 0;
}
#facebook:hover
{
background-position: 0 -26px;
}
#facebook span
{
display: none;
}
@hendersonben: I think the problem is that your a element has 15px top and bottom padding (caused by your ‘#sidebar .sidebar-menu a’ CSS rulle I think). This will make the link/button taller than it should be.
@beelzebomb, @matt
thanks fellas… i picked this project up half-way through and am just trying to implement band-aids where necessary.
based on the css the previous designer used to build his menus and not wanting to overcomplicate things, i just decided to use some javascript for an easy roll-over.
i see the benefit in using a sans-javascript hover state — and will implement your process the next time around when i can control things from the beginning.
once again, thanks for the help and the prompt replies.
Great tutorial MattΓ’β¬βeasy to follow.
I was looking at the code from this site which implements the same sort of thing except they use one image for multiple nav buttons:
http://www.bluevalentinemovie.com/
I can’t figure outΓ’β¬βfrom viewing their codeΓ’β¬βhow the rollover has a gentle fade to it though.
Ahh, the fade is done with javascript.
@psound: Actually you can do that with CSS3 transitions these days:
http://www.cardeo.ca/2010/creating-a-fading-link-transition-with-css3
@Matt
Cool, looks nice in Safari. Wish it was supported by the rest.
Can I slow the image transition speed between the different image positions so that instead of jumping from one position to another, the process can be defined in seconds?
I note this: http://www.cardeo.ca/2010/creating-a-fading-link-transition-with-css3 but is fading the same as slowing the speed? Furthermore the above technique doesn’t work with FF or IE, which are the most commonly used browsers, therefore the technique is useless from my viewpoint.
Here is my code which I adapted from your article:
If you can tell me how to slow the transition speed and where to put that code then that would be great. I’m not an expert at website coding so if you could keep your instructions simple that would be very much appreciated.
Thanks.
@psound: Works in FF4, Opera 10 and Chrome too. Not sure about IE9.
@SU45: See above! You can use a jQuery fallback if you need IE support.
This was an excellent and very easy-to-follow tutorial. I had my own version of this rollover going in less than 5 minutes.
Thanks!
@web sara: Thanks, glad it helped. π
Matt
This is very nice but I like to add JavaScript (jQuery) for extra animation/transition effects. With a bit of jQuery and CSS3 you can create a button like the one in this example without any need for graphics files – gradient, border-radius, box-shadow, etc.
@dr_smith: Yes, very true – you can do a lot with CSS these days. In fact I saw a nice CSS button just today:
http://line25.com/tutorials/how-to-create-a-stylish-button-entirely-with-css3
Hi, I’m trying to get this code to work but no image is showing at all. If you could shed any light I’d appreciate it, website is http://www.flawless-magazine.net/contributions and code I’m using is:
<style>
#current { display: block; width: 146px; height: 30px; background: url(“http://www.flawless-magazine.net/images/menu/current.jpg”) no-repeat 0 0; }
#current:hover { background-position: 0 -30px; }
#current span { position: absolute; top: -999em; }
</style>
<p>
<img src=”http://www.flawless-magazine.net/images/logo.jpg” height=”150″ />
</p>
<a id=”current” href=”http://www.flawless-magazine.net/” title=”Current issue”><span>Current issue</span></a>
From what I can see I’ve replicated your sample code exactly, the only thing I can think is that I’m putting this in as an .inc file but I can’t see why that would affect it.
Steve
@steve_reddin: That URL gives me a 404 error. I guess you’ve (re)moved the page?
Hi I just had a a quick question. I followed the article and got everything working but i would like to center all the images within the ul tag.. can you help me out ?? thanks..
@mediadm: You’ll need to be more specific. What ul tag? Centre horizontally or vertically?
HI! I am a total newbie to all things web-related. I am trying to teach myself…. Can I implement these buttons in a widget within a sidebar of a WordPress site? Where in the stylesheet specifically would I insert the css code you mentioned? Would I put the html in the sidebar widget directly???? I am clueless! hahaaha!
Ok, I think I must have figured it out, because here’s my result:
http://medicaredayton.com/medicare-made-simple/medicare
@mamaneace: That works!
You can put the CSS practically anywhere. Personally I would create a separate CSS file and link to it in the theme head section.
Hello,
In my sidebar widget, I have put up an image of my face. Now my need is when I take my mouse cursor over this image, it should change to new image.
In my sidebar widget, I have written following:
While in Custom CSS, I have written following code:
But this is not working. It doesn’t do anything when I take my mouse over my pic.
What am I doing wrong? Any help will be appreciated.
Soham
@soham100: You need to combine face.jpg and proudIndian.jpg into a sprite and add it as a background image to your link in the CSS. Then shift the image position on hover, as shown in the article.
Matt,
Thanks for the great tutorial. Very easy to follow. I’m having trouble trying to get my background image to display. I’m working in a pre-made WordPress theme, so I suspect there may be something conflicting within the CSS, but I cannot figure it out. Span is also not responding to CSS styling. Would you mind taking a look?
Here’s a link to my page: http://www.miserbros.com/rollover
CSS: http://www.miserbros.com/wp-content/themes/DICE/css/main.css
Here’s my code:
Any help you could give me would be greatly appreciated. thanks.
wes
Hey there,
I think I’m having the same issue as mediadm. All the text in my div where I’m placing the button is centered. The button, however, hugs the very left edge of the div.
Is there a way I can get the button to align in the center of the div like the rest of the text in the div? (another newb here, glad I found your site!)
Thanks!
-Matt
Sorry Matt,
Don’t mean to steal any thunder but I’ve been getting these emails a lot so I see how busy you must me answering all these questions.
@omdata Post an example of your CSS and the HTML snippet where you’re trying to utilize it. This should give everyone a better perspective of your issue. While you are at it check your background-position and ensure that is set correctly. Thanks :-D.
K, thanks for the quick response! Here’s the html:
and here’s the css, it’s pretty much unaltered from the post with the exception of the object dimensions:
I tried containing the image in its own div, and centering that, but I apparently don’t know how to do it (or even if that’s viable). The closest I came was using a margin-left to shove the button over, but I think that’s probably not the most elegant/simple solution and I’d love to know how to do it properly.
Is your button image (sprite) exactly 138×106? If it is not, that is the reason the sprite is hugging to the left. I also don’t understand why you say the text is centered? Are you using the <span> tag for the text view or is the text embedded into the image sprite that you are using?
Yes, the image res is exactly 138 x 106.
What I mean when I say the text is centered is that the rest of the text contained in the “navbarleft” div (and therefore, all the rest of the contents of that div) is centered. I apologize, I probably should have also attached the css for those other properties. Here is the code for the page in its entirety:
I appreciate your assistance!
OK! Got it! Check out these two modified selectors:
Basically, you are going to make the #orderdvddiv 100% of the width of it’s parent, #navleftbar, and then down in #orderdvd you are going to set it’s margin to “0 auto” which will set the top margin to nothing (because we don’t care about it) and the right margin to auto, which will automatically get the distance of the block element’s right and left position of the parent and then set the pixel amount to the half of that. Hopefully that works for you.
Check it in IE 8 and below because I am not sure if it will work. I am pretty sure it will since we have previously stated to set the element’s display as block.
[Edited by cwalkdawg on 19-Aug-11 14:04]
Sweet! Looks like it should work just fine π Thanks Dawg! I think I will have to use that code on a number of different elements as I continue to work, so I really appreciate your help! (I’d much rather know how to do it correctly than to have to jackleg it every time…)
Yeah, I work on a Mac, and I”ve kinda been dreading see what’s gonna happen when I finally test it on the PC in our office in IE…
I just looked it up and using the display block should work fine on at least IE8.
I work on Linux, Mac, and Windows and it always gets mixed up or messed up somewhere. Just gotta look for the fixes.
Glad I could help.
Are there any applications for Mac that simulate IE environments to test code on that you would recommend?
http://ipinfo.info/netrenderer/
Give this site a look at. I haven’t used it myself because I test with an application in Vista, but supposedly you can render the pages online.
Cool, thanks again!
@cwalkdawg: No problem at all, I really appreciate you helping out π
@Ladger: Works for me! I guess you fixed it.
Awesome article and I use this everywhere. However, there is one thing I don’t get. On Hover we are shifting the image “UP” but the CSS seems to indicate moving it to the “Left”. I’ve seen other (less elegant) CSS that actually does the same thing and actually uses “background-position: left -23px”.
Why does this cause the image to move UP instead of to the LEFT?
Thanks for awesome articles.
@ltyre
Background-position specifies vertical and horizontal. It does not specify a direction. Thus the
declares that the position of the background image will sit to the left of the element and -23px from the top edge of the element.
So if you want to shift an image to the left by say, -23px, you would say
http://www.w3schools.com/cssref/pr_background-position.asp
Hi Matt,
I see you’ve been answering questions on this tutorial for quite some time…good on you!
I have an issue. I’ve followed the code and have the button sitting in my webpage but it will not move to the second position when hovered over.
I’ve uploaded the temporary page here:
http://www.nickworley.co.uk/index_split.html
HTML Code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset=”UTF-8″>
<title>Nick Worley</title>
<link href=”CSS/2_Column_Layout.css” rel=”stylesheet” type=”text/css”>
</head>
<body>
<div id=”container”>
<header id=”sidebar”>
<img src=”Images/logo.png” width=”150″ height=”84″>
<p></p>
<p></p>
<p></p>
<a id=”Colliery” href=”Colliery.html” ><span>Colliery</span></a>
</header>
<div id=”maincontent”>
<img src=”Images/Architecture/Colliery/IMG_2997.jpg” width=”800″ height=”800″>
<img src=”Images/Architecture/Colliery/IMG_3002.jpg” width=”800″ height=”800″>
<img src=”Images/Architecture/Colliery/IMG_3057.jpg” width=”800″ height=”1043″>
</div>
</div>
CSS Code:
#container {
width: 1000px;
/* max-width: 98%;*/
margin-left: 230px;
margin-right: auto;
position: relative;
min-height: 100%;
}
#sidebar {
position: fixed;
z-index: 20;
width: 180px;
padding-top: 100px;
padding-left: 50px;
/* text-align: left;*/
left: 0;
border-style: none;
}
#maincontent {
padding-right: auto;
padding-top: 100px;
}
img {
border-style: none;
}
#Colliery {
display: block;
width: 140px;
height: 14px;
background: url(“../Images/Colliery.gif”) no-repeat 0 0;
}
#Colliery:hover {
background-position: 0 -14;
}
#Colliery span {
position: absolute;
top: -999em;
}
I”ve pasted all of the code just in case there’s some conflict with the page layout and the rollovers….
The original image is 140px long x 28px high.
Any help really appreciated.
Cheers/
@nickworley
What’s up brother? Nice pictures!
I scoped your CSS that you posted and then the CSS on the actual site. Are you sure the “hover” declaration for Colliery is in the CSS on the site? I didn’t see one.
@cwalkdawg
Thanks for the reply.
I actually solved it tonight. I definitely had the hover declaration for Colliery – the problem appeared to be in the pixel movement. I definitely also had that correct, checked it several times, but saw another example using center bottom. Changed it to that and it worked.
Now need to get my head around a DWT for structuring the site / applying changes across the board later down the line as I add more projects.
Thanks for the shout on the images.
Hi there! First of all: great tutorial. I’m an old school web designer and I am always struggling moving to old html/tables/javascript stuff to a cleaner css life.
Thanks again!!
[Edited by grimorg80 on 05-Jan-12 12:23]
@grimorg80: Thanks for the feedback – I’m glad you liked the tutorial π
Great tutorial. I am trying to combine this tutorial with this one here: http://www.elated.com/articles/html-form-buttons/ but having a challenging time.
Basically, I have a form with 3 rollover buttons. Each button has a unique name, i.e forward, reverse, add_user. The form calls a php file called processor.php and within processor.php, depending on what was clicked, the appropriate action happens with the processor.php file.
I cannot get both the rollover image and the multiple buttons to work on the same page. for some reason, the $_POST[‘add_user_x’], $_POST[‘forward_x’],$_POST[‘reverse_x’] are all empty when I use a rollover, but work fine when I do not use a rollover….
Any ideas on how I can merge both of your techniques?
Thanks!
@bullmoose: You’ll need to post the URL of your form page so we can see the problem.
@matt, thanks for the response and here is the page:
http://www.speedylines.com/test/store_console.php
Regards,
bullmoose
@bullmoose:
isn’t valid markup.
You need to give a <button> element an id, then select the element in the CSS using its id.
eg:
Your CSS needs to style the element by removing all borders and outlines, then it needs to add the background image sprite, as in the original tutorial. It’s not always possible to get this looking good on all browsers, especially older ones. You may be better off using regular <a> elements and attaching JS click handlers to them to submit your form.
Thanks for this tutorial. I followed your instructions to make rollover buttons for http://www.mikhaililiev.com and they look great in most browsers — but the sprites don’t line up properly in IE. Most of them appear to be 1 pixel off on the top or the bottom. I’ve double checked the sizes and they appear to be correct. AND — if I redo the sprites so they look right in IE, then they are off in the other browsers:(
Is there something wrong with my code? Or is there a workaround for IE?
Here is the html and css for three buttons that aren’t working on the home page:
Many thanks for any help!
<a id=”fictionbutton” href=”fiction.html” title=”Fiction”><span>Fiction</span></a>
<a id=”poetrybutton” href=”poetry.html” title=”Poetry”><span>Poetry</span></a>
<a id=”financebutton” href=”finance.html” title=”Finance”><span>Finance</span></a>
#fictionbutton
{
position: absolute;
top: 500px;
left: 115px;
display: block;
width: 236px;
height: 100px;
background: url(“images/fictionbutton.jpg”) no-repeat 0 0;
}
#fictionbutton:hover
{
background-position: 0 -100px;
}
#fictionbutton span
{
position: absolute;
top: -999em;
}
#poetrybutton
{
position: absolute;
top: 500px;
left: 351px;
display: block;
width: 187px;
height: 100px;
background: url(“images/poetrybutton.jpg”) no-repeat 0 0;
}
#poetrybutton:hover
{
background-position: 0 -100px;
}
#poetrybutton span
{
position: absolute;
top: -999em;
}
#financebutton
{
position: absolute;
top: 500px;
left: 538px;
display: block;
width: 178px;
height: 100px;
background: url(“images/financebutton.jpg”) no-repeat 0 0;
}
#financebutton:hover
{
background-position: 0 -100px;
}
#financebutton span
{
position: absolute;
top: -999em;
}
This worked great to create top menu line “buttons” that are merely lines of text that appear to change colors. I figured I’d try to create some larger rollover image buttons that use a dual Gif image that is 360 wide x 360 tall… with a 180 pixel B&W image over a 180 pixel color version of the same image… the idea being the picture gets colorized when you hover over it.
For some reason, I can’t get the thing to work. The boxes for the images are there, but the images won’t come in. If I view the HTM in a browser, the hyperlinks attached to the boxes work fine to send you to another HTM.
I’ve checked the call-out in the HTM, the CSS file, and the link, but I can’t find the problem. I’ve even got one of the smaller working buttons in there to compare to. That image loads fine.
Is there a maximum size rollover image that this trick can no longer handle? Can I send a bunch of stuff to someone to look over?
Thanks,
Wojo
Never mind… I renamed some files and it works now (but I never did find my typo.) By the way, the larger image rollover buttons work fine.
Wojo
Hello
Just a quick message to thank you for the great tutorial : )
I’m quite new to coding etc (but very interested to try and teach myself) and used your tutorial to add a rollover state to my social media buttons (www.mattt.com.au) on my Shopify website.
Thanks again, much appreciated.
Cheers
Matt
Thanks for this post; you solved my problem.
I was looking for a way to create a rollover for WordPress (WP) pages. Your code worked great, but I found the visible text link stayed with the graphic in WP (as the WP page is just a part of the entire web page code).
I solved the problem by adding a class to the CSS, changing the color of the links to the same color as the background of the page (in this case white).
Then in the WP page (in text view) the link looked like this:
WARNING: If you use this in WP, you should be aware that WP messes up your code when you jump between VISUAL and TEXT view. You should do all your layout that you want in visual, then switch to text to add your rollover image – but beware, clicking on the visual tab could mess your button up. Instead, use the Preview Changes button.
Again, thanks.
More about Image hover effects…
http://www.corelangs.com/css/box/hover.html
Mark
[Edited by markjeggar on 21-Jun-14 01:31]
Thanks.. It’s an easy way to create buttons.