CSS FAQ

  1. What's wrong with Internet Explorer?
  2. Why are my images not contained within their parent div (in FF)?
  3. How do you show which page you're on (in a menu)?
  4. What's the difference between 'class' and 'id'?
  5. How do I get rid of the gap under my image?
  6. Why are there gaps above and below my form in IE?
  7. I made a 10px-high div, but IE makes it 20px high...
  8. How do I make my div 100% height?
  9. How do I centre my page?
  10. How do I get my footer to sit at the bottom...?
  11. How do you target a certain browser?
  12. How can you set a minimum width for IE?
  13. Why doesn't 'vertical-align' work?
  14. Where did my image go?!?
  15. How do I get rid of the (blue) border around image links?
  16. How do you make a whole div into a link?
  17. How do I have links of different colours on the same page?
  18. How do you make a tooltip that appears on hover?
  19. Why does my content shift to the left on some pages (in FF)?
  20. How do I make a gradient with CSS?
  21. How do you get your menu to stay fixed like that?
  22. How do you get your background to stay fixed like that?

... and non-CSS questions :

  1. How do you have an external file (like a menu) on every page?
  2. I'd like a different image depending on the time of day...
  3. How do you have something random - like a random background?
  4. And how about a set of rotating links, where one is an image?
  5. How do you open a link in a new window?
  6. How do you open two new windows?
  7. Some select boxes go to a link when selected. How's that done?
  8. How do you get the little icon in the browser's address bar?
  9. How can I test my site in IE5x browsers?
  10. I want to automatically re-direct users to my new address.
  11. How do you set and read a cookie?

What's wrong with Internet Explorer?

At the moment, many people are still struggling with IE6. IE7 fixed many of IE6's bugs(Yaay!) and IE8 is on its way. However, there are still some problems with that one too. Anyway, I think it's fair to say that IE6 is a bit crap (and IE7 still has some problems)... and here are a few reasons why:

  • IE6 treats 'height' as other browsers treat 'min-height'.

    The 'height' property is supposed to fix the height of an element - if there's too much text for the element, you should use the 'overflow' property to allow the user to scroll to see the rest of the content. IE doesn't do this though - if there's too much text, IE just makes the div bigger! Moron.

  • IE6 only applies pseudo-classes like ':hover' to the 'a' tag.

    This is bloody typical. The :hover pseudo-class is particularly useful for things like CSS dropdown menus and highlighting (data) table rows, but IE only recognises it when it's on the 'a' tag. Stupid boy. For example, the Suckerfish menu on this site works fine in Firefox, but IE needs some javascript to get it to work properly. It's not always good to build menus with javascript though, as some people have it disabled.

    Other things IE6 doesn't recognise include ':after', ':before' and ':target'...

  • IE6 treats floats differently to other browsers

    It clears floated elements, which sometimes seems like a positive thing as it causes fewer problems for developers, but if it's doing things wrongly, it can't be good...

    (With other browsers, developers have the kind of problem talked about on my Clearing floats page).

  • The 3px jog

    IE6 adds 3px of padding to the right-hand side of a left floated element when there is a static or relative-positioned element next to it. You keep messing around with it - setting margins to zero, trying to move things around a little and all sorts, but you can't fix it - there's a 3px gap between the left floated element and the element to its right. 'Bloody Microsoft!' you think...

    Let's say your left-hand float is 200px wide and the next element has 'margin-left:200px;', which puts it in the right position in good browsers but 3px further right in IE. Well, here's how to fix it. (This wasn't my idea by the way, I copied it from Paul's CSS FAQ at Sitepoint). Put this in an IE-only style sheet and link to it with IE conditional comments.

    CSS
    #left {
    margin-right:-3px;
    }
    #right {
    height:1px;
    margin-left:197px;
    }
  • Quirks mode

    Developers sometimes don't insert a proper DTD at the top of their page or put something else - like an XML declaration - before the DTD. This causes IE to go into quirks mode, which is, well... quirky.

    This uses what they call the 'broken box model'. Basically, the standards say that the actual width of a block-level element is width + padding + border. The broken box model says that the actual width is whatever you put for 'width' in your CSS - the borders and padding go inside that.

    This difference can cause all sorts of problems.

  • 'hasLayout'

    The 'wise' people at Microsoft included a property called 'hasLayout' in IE and this is the cause of many rendering problems, such as disappearing text/backgrounds and elements appearing in seemingly inexplicable positions. There are certain properties and values that will return 'hasLayout' as true (see the link), and one of those is 'display:inline-block'. You can often fix hasLayout problems by using this.

    CSS
    #element{
    display:inline-block;
    }

    Of course, this may cause other problems, but it often usually doesn't. If you do have problems with that method, you can target IE with IE conditional comments, something like this:

    <!--[if IE]>
    <link href="ieonly.css" rel="stylesheet" type="text/css">
    <![endif]-->

    This will feed an IE-only style sheet to IE. If you need to force hasLayout on an element, you can put the rule in there. One rule that forces hasLayout is 'zoom:1;'. It doesn't do much else, so you could use that. It's not valid code, meaning that it wouldn't pass the W3C validation, but the validator doesn't read anything in IE conditional comments and, let's face it, you're using it as a hack so does it really matter?

    (A great article all about 'hasLayout')

  • IE6 doubles margins on floats

    If you have an element that is floated left and you give that element a left margin, IE6 decides to double that margin. That can be fixed by adding 'display:inline' to the rules. Why that fixes it, God only knows - but it does.

  • You can't make a div that's smaller than the font-size in IE6

    There isn't usually much need to do this, but I've seen lots of people trying to make very small divs so that they can have some kind of divider (I'd recommend using a border or a background-image in another element).

    If you make a div with 3px height, IE6 will give you a div which is about 20px tall - the height of your font. To fix this, you just need 'font-size:0;'.

  • IE6 doesn't support...

    • position:fixed

      If you're smart, then you're viewing this site in a good browser and you'll see my menu on the left as I intended it to be - fixed on the left-hand-side of your screen. If you're using IE6, you probably can't see my menu because it's scrolled up out of view - because IE is crap.

    • min-width/max-width or min-height/max-height

      This is discussed below.

    • :target

      There's a nifty way of doing what I do on my Switching content page without javascript. It uses ':target' and of course doesn't work in IE6.

      Here's an example:

      These paragraphs are all set to 'display:none' in the css, and the ':target' style says 'display:block'.

      Here's the CSS : CSS
      #t-text p{
      display:none;
      }
      #t-text :target {
      display:block;
      }

      It doesn't get much simpler than that does it?

      The only problem with this - apart from the fact that it doesn't work in the most widely-used browser - is that it kind of needs to be near the top of a page to get the desired effect. As you can see here (well, I hope you can see what's going on) the hidden element appears when the navigation link is clicked, but it also puts that element at the top of the viewport, which we might not want. The effect should work well if your page is small (example).

    • :before or :after or content

      "This is new!" (:before) and "This is new too!" (:after).

      HTML
      <p><span class="new-b">"This is new!"</span> (:before) and <span class="new-a">"This is new too!"</span> (:after).</p>
      CSS
      .new-b:before, .new-a:after {
      content:url(new.gif);
      }
    • :first-child

      This paragraph is a first child and should look different from the second paragraph.

      This is the second paragraph.

      CSS
      #first-child-ex p:first-child {
      font-style:italic;
      color:#CC0000;
      }
    • <q>quotes tags</q>

      'q' tags give us quotation marks in Firefox, but not in IE.

      Of course the people don't want war. But after all, it's the leaders of the country who determine the policy, and it's always a simple matter to drag the people along whether it's a democracy, a fascist dictatorship, or a parliament, or a communist dictatorship. Voice or no voice, the people can always be brought to the bidding of the leaders. That is easy. All you have to do is tell them they are being attacked, and denounce the pacifists for lack of patriotism, and exposing the country to greater danger. -- Herman Goering at the Nuremberg trials

    • attribute selectors

      These define styles by an element's value, for example, I have style rules for 'a' tags in my stylesheet, but this extra rule for links to Google will overrule those rules.

      CSS
      a[href="http://google.com"] {
      color: #CC0000;
      font-size:1.1em;
      border:1px dashed gray;
      text-decoration:none;
      }

      This can also be useful for forms. Maybe you want a different border for submit buttons...

      CSS
      input[type="submit"] {
      border:2px solid navy;
      }

I'm sure this doesn't cover all of IE6's problems, but it does show that it's a bit crap.

Why are my images not contained within their parent div (in FF)?

You need to clear the floats.

How do you show which page you're on (in a menu)?

Funny you should ask - my 'Showing current page' page tries to answer that question.

If PHP is not available to you, you could use the cascade. Put an id in your body tags and an id in each of your 'a' tags for the links.

Let's say on page one you have this:

CSS
<body id="page1">
....
<a id="page1link" href="page1.htm">page one</a>
...
</body>

In your CSS, you can have something like this:

CSS
#page1 a#page1link {
color:purple;
}

What's the difference between 'class' and 'id'?

As a person, you may have an ID card - a passport, a driving license or whatever - which identifies you as a unique individual. It's the same with CSS. If you want to apply style to one element use 'id' (e.g. <div id="myid">). In the stylesheet, you identify an 'id' with a '#' ie. '#myid'...

As a person, if you are in a class, you are one of many. It's the same with CSS. If you want to apply the same style to more than one element, use 'class' (e.g. <div class="myclass">). In the stylesheet, you identify a 'class' with a '.' ie. '.myclass'...

If id's are more restrictive than classes, then why not just litter your page with classes? Well, I think the main thing is that it's simply wrong. You don't put headings in 'p' tags - you use 'h1', 'h2', etc. You don't (or shouldn't) make a list by writing asterisks or the little divider bar ( | ) - you use list tags ('ol'/'ul' + 'li') . You don't say that your footer is part of a class of elements called 'footer' - that's just stupid - you can't have more than one footer - it can't be a class. Of course, practically, the effect is about the same - the rules are applied - but that's not the point - it's semantically wrong to do it that way... However, if you try to give more than one element the same id, you will have problems - so don't do it.

An element may have an id and a class, but that's usually not necessary. You can also give an element two classes if you need to - like this : class="class1 class2". It can be very useful. Needless to say, you can't give an element two id's.

Another difference is to do with power. You can give an element an id and a class, but if any of the properties of the two conflict, the id style will win. Ids are more powerful than classes.

One more useful thing about id's is that they can be used as a link reference. Many people still think that you need named anchors to make links within a page, but that's simply not true - in fact, the name attribute is deprecated in XHTML except for in forms. One example of using id's as link references is this page. There are no named anchors on this page - the questions at the top of the page link to the id's of the divs that the answers are in.

How do I get rid of the gap under my image?

Images are inline elements, which means they are treated in the same way as text. Most people kind of know this - they know that if you use 'text-align:center' on an image it will be centred. What many people don't realise is that this means you will have a gap underneath an image. This gap is for the descenders of letters like j,q,p,y and g. To get rid of this gap you need to make the image block-level - like this : CSS
img {display:block;}

One problem that this can cause is when you want to have a few images next to each other - if they are block-level, they won't be next to each other. To get around that, you can use float:left. Of course, this might present another problem - maybe you don't want the image to float left. In this case, you can use an unordered list like this :

CSS
ul, li {
list-style-type:none;
padding:0;
margin:0 auto;
}
ul {
width:150px;
}
li {
float:left;
}
HTML
<ul>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
<li><img src="wine.jpg" height="50" width="50" alt="wine" /></li>
</ul>

This will give us this :

  • wine
  • wine
  • wine
  • wine
  • wine
  • wine
  • wine
  • wine
  • wine

If you do this, don't forget to clear the floats.

Just for reference, this is what it looks like without 'display:block' :

  • wine
  • wine
  • wine
  • wine
  • wine
  • wine
  • wine
  • wine
  • wine

Why are there gaps above and below my form in IE?

A lot of the time, when you find gaps that you can't account for, they are due to the default styles of different browsers - especially the margins and padding. IE gives forms large top and bottom margins, while Firefox doesn't. It's like with lists - you'll find bigger padding and margins for lists in IE than in Firefox. Paragraph margins are different, as are the margins on heading tags (h1,h2, etc).

A good way to not get caught out by these problems is to set all margins and padding to zero at the top of your stylesheet and then add them as and when you feel the a need for them, in that way, any margins and padding will be the same in different browsers.

CSS
* {
margin:0;
padding:0;
}

I made a 10px-high div, but IE makes it 20px high...

Yeah - pain in the arse, isn't it?

This problem sometimes comes up when you make a div just to contain the bottom border of a box, or something like that. In this situation, there's no text in the div, but IE won't let the height of the div be smaller than the line-height (which usually depends on the font-size). The answer is to set the font-size to zero, reduce the line-height, or use 'overflow:hidden;'.

CSS
#oneway {
font-size:0;
}
#anotherway {
line-height:0;
}
#yetanotherway {
overflow:hidden;
}

How do I make my div 100% height?

You need to know what the 100% is of, so the parent div must have a height set. One problem that people often come up against is making the main page fill the screen if there's little content. You can do that like this :

CSS
body, html {
height:100%;
}
body {
margin:0;
padding:0;
}
#wrap {
position:relative;
min-height:100%;
}
* html #wrap {
height:100%;
}

Here, the #wrap div goes around your whole page - it's like a sub-body.

You need to use 'min-height' rather than 'height' for Firefox because otherwise it will set it to 100% of the viewport and no more. Internet Explorer, being well... crap, treats 'height' as it should be treating 'min-height' which it doesn't recognise. You can target IE6 by preceding your code with ' * html ' or target all IE versions by using conditional comments.

To make floated divs within this #wrap div 100% of the #wrap div... well that's more difficult. I think the best way is to use the 'faux columns' technique which basically means that you put the background in your body rather than your columns. If the body has columns and your floats don't then it looks like your floated content is in a column that stretches to the bottom of the page. I've used this technique in my layout demos.

The problem is often not that the columns aren't 100% height, but that they're not equal lengths. Columns usually don't start from the top of the page and end at the bottom - there's often a header and a footer or sometimes, more interesting designs don't have a recognisable columnar layout, but do require div boxes to be equal heights. This can be done with the aid of a couple of images and some css or with some javascript.

This leads to more questions like...

How do I centre my page?

This is very easy. If we take the code in the last question and change it to this : CSS
body, html {
height:100%;
}
body {
margin:0;
padding:0;
}
#wrap {
position:relative;
width:780px;
margin:auto;
min-height:100%;
}
* html #wrap {
height:100%;
}
you get a page that fits an 800x600 resolution screen without a horizontal scrollbar, which will be centred at higher resolutions.

To vertically-centre a whole page, Paul O'Brien's demo uses CSS table display properties and a hack for IE, which is crap (IE that is - not the hack).

After that...

How do I get my footer to sit at the bottom...?

OK - not enough room in the header for the full question (bad design, you see) - this should read, How do I get my footer to sit at the bottom of the page when the content of my page doesn't fill the screen?

If we stay with the code from the last two questions, we just need to add a couple of things. Place the footer at the bottom of the #wrap div with absolute positioning. It will go there because the #wrap div is set to 'position:relative;' so that its children are placed relative to it. The problem here is that if you have content down at the bottom of your page, the footer will sit on top of it. You can sort this out by giving your content another 'inner-wrap' div which has enough bottom padding to make space for your footer. Like this :

CSS
body, html {
height:100%;
}
body {
margin:0;
padding:0;
}
#wrap {
position:relative;
width:780px;
margin:auto;
min-height:100%;
}
* html #wrap {
height:100%;
}
#inner-wrap {
padding-bottom:80px;
}
#inner-wrap:after {
content:" ";
display:block;
clear:both;
}
* html #inner-wrap {
height:1px;
}
#footer {
position:absolute;
bottom:0;
width:100%;
height:50px;
}
HTML
<div id="wrap">
<div id="inner-wrap">
...content goes here...
  </div>
  <div id="footer">Footer</div>
</div>

The first bit is the padding, the second bit is to make the footer clear any floated content and the third bit is to stop IE from messing things up for everyone. You can see this in action here.

How do you target a certain browser?

IE6 can be targetted by preceding your properties with '* html'. For example...

#nav {
position:fixed;
}
* html #nav {      /* this will target IE */
position:absolute;
}

Another way to target IE is with conditional comments. Put this (below) in the head - just before the closing tag - and put anything you want to be directed only at IE in another stylesheet.

<!--[if IE]>
<link href="ieonly.css" rel="stylesheet" type="text/css">
<![endif]-->

(More about IE conditional comments)

If you need to target IE5x...

#wrap {
width:760px;   /* for IE5x */
w\idth:780px;   /* for all other major browsers */
}

And if you're worried about Opera, this seems to work...

#nav {
position:fixed
}
@media all and (min-width: 0px){ #nav {position:absolute;} /* this should target Opera */ }

There's a huge list of possible CSS filters/hacks at centricle.

How can you set a minimum width for IE?

You probably know that to set a minimum width, the CSS property is 'min-width'. This can be very useful and works well in good browsers. However, our friends at Microsoft didn't bother telling IE about it, so IE doesn't understand 'min-width'. However, it has a proprietary property (try saying that three times fast after a few whiskies!) called 'expression' which allows us to feed it javascript via a stylesheet. Below is how we can set a (780px) minimum width for IE...

<!--[if gte IE 5]>
<style type="text/css">
body {
width:expression(documentElement.clientWidth < 780 ? (documentElement.clientWidth == 0 ? (body.clientWidth < 780 ? "780px" : "auto") : "780px") : "auto" );
}
</style>
<![endif]-->

As the property is non-standard, it won't validate with the W3C validator, so if we put it in the head like this (above) - in an IE conditional comment - the validator will ignore it and the page will get a clean bill of health.

Why doesn't 'vertical-align' work?

It does - you're probably just misunderstanding what it does and how it works.

Below, there's a small demo of what 'vertical-align' does. You won't be surprised to hear that Firefox and IE give slightly different results.

This is what the specs say :

Value: baseline | sub | super | top | text-top | middle | bottom | text-bottom | <percentage> | <length> | inherit
Initial: baseline
Applies to: inline-level and 'table-cell' elements
Inherited: no
Percentages: refer to the 'line-height' of the element itself
Media: visual
Computed value: for <percentage> and <length> the absolute length, otherwise as specified

This property affects the vertical positioning inside a line box of the boxes generated by an inline-level element.

The red border is an inline element.

baselinesubsuper toptext-topmiddle bottomtext-bottom 20%30px;-50px;

Here's the same thing in a block-level element. You can see that 'vertical-align' is related to the line - not the div.

baselinesubsuper toptext-topmiddle bottomtext-bottom 20%30px;-50px;

Often, when people have problems and think, "Why doesn't the vertical-align work?" what they really need is something else. Sometimes, they might need to use absolute positioning - like below. The green box is 'position:relative;'. The span is absolutely positioned within the box.

position:absolute; bottom:0;

Other times, what's required is to set the line-height. Maybe there's a menu which is marked up as an unordered list... The list-items are block-level and if the height of the <li> is more than the line-height, the text will not be positioned in the centre of the <li>. So, if you make the line-height the same as the <li> height, you get what you want.

  • This is without the
  • line-height adjustment
  • This is with the
  • line-height adjustment

...but how do you centre a whole page vertically?

Where did my image go?!?

Sometimes, images just disappear. You put them in the html, upload the file to your server, and then check it in a browser and it's not there. More mysterously, when you check the source - it's not there either. This is usually because of some kind of ad-blocking software (often Norton). The most common cause seems to be naming your image 'banner.jpg'. After that, it could be the image size - certain dimensions are blocked as they are typical ad-banner sizes. So, if you come across this problem, try changing the name or size of your image.

Another thing that happens is when a background disappears - but only in IE. This has got something to do with IE's 'haslayout' property. MSDN's info says that 'position:absolute' returns true for 'haslayout', but I find that if you use 'position:relative' you'll get what you want.

How do I get rid of the (blue) border around image links?

Like this :

a img {
border:none;
}

How do I have links of different colours on the same page?

This is bloody easy this is. I think if you don't know how to do this, you should spend some time at W3Schools. Having said that... There are many ways to do this, but I think the best way is to use the cascade. I often see people recommending people to use classes in their 'a' tags like this : CSS
a.red {
color:red;
}
a.blue {
color:blue;
}
HTML
<a href="#" class="red">A red link</a>
<a href="#" class="blue">A blue link</a>
This is a valid way to do it, but usually, this isn't what a page looks like - two links next to each other with different colours - it's usually something like a menu with one kind of link and main body text or another menu with different links. In this (normal) situation, I think it's better to go higher up the cascade to style the links. Something like this : CSS
a {
color:blue;
}
#menu a {
color:red;
}
HTML
<ul id="menu">
<li><a href="#">A red link</a></li>
<li><a href="#">A red link</a></li>
</ul>
<div id="content">
<p>There's <a href="#">a blue link</a> here.</p>
</div>

How do you make a tooltip that appears on hover?

The most simple way is to use the 'title' attribute like this...

HTML
<span title="Example of the title attribute in use">like this</span>

..or you can do something like this : Karl MarxAuthor of Das Kapital and The Communist Manifesto

CSS
a.tooltip {
position:relative;
cursor:help;
}
a.tooltip span {
display:none;
position:absolute;
top:1.5em;
left:0;
width:15em;
padding:0 2px;
}
a.tooltip:hover {
display:inline;
}
a.tooltip:hover span {
display:block;
border:1px solid gray;
background-color:white;
}
HTML
<a class="tooltip" href="#n">Karl Marx<span>-info goes here-</span></a>

Without this part... a.tooltip:hover {
display:inline;
}
...it won't work in IE.

The "#n" in the link is to prevent the page from jumping to the top if the link is clicked (I got this idea from Stu Nicholls). The "href" part is necessary as it won't work in IE without it.

Why does my content shift to the left on some pages (in FF)?

That'll be the pages with more content? The ones that have a vertical scrollbar? If you look in IE there's probably a white space on the right where there would be a scrollbar if there were enough content to require one. In Firefox, the scrollbar appears when it's needed and the viewport becomes about 20px smaller, so the content seems to shift to the left when you move from a page with little content to one with lots of content. It's not a bug or something that needs to be fixed, but it does confuse and irritate some developers.

If, for some reason, you'd like Firefox to always have scrollbars - whether they're needed or not - you can do this :

CSS
html {
height:100.1%;
}

How do I make a gradient with CSS?

If you want a gradient for your background, you can make a 1px-wide, 600px-high (or however long you need the gradient to be) gradient image in the image editor of your choice, put it in the background of your body and repeat-x. Like this.

How do you get your menu to stay fixed like that?

See here

How do you get your background to stay fixed like that?

Here's how it's done on this page. (Notice the word 'fixed' at the end there).

CSS
body {
background:white url(myimage.jpg) no-repeat 65% 70px fixed;
}

...and non-CSS questions :

How do you have an external file (like a menu) on every page?

This is done with server-side scripting, which means that the server puts the code into the page before it reaches the browser. Some people use javascript to do this, but this is a bad idea as some people (about 10%) have javascript disabled, so a lot of people won't see anything - just an empty space.

The best way has to be with PHP. First check that your server supports php - most good commercial web hosts support php, but you do come across a few that don't. Then, save your pages with a .php extension (so instead of say 'mypage.htm' you have 'mypage.php'), save your menu (just the menu html - no DTD, no 'body' tags - nothing but the html of the menu) as 'menu.php' (or menu.htm, menu.html or menu.txt) and add this on every page in the place where you would normally have your menu : <?php include 'menu.php'; ?> (Here's what the manual says).

If your server doesn't support PHP you should be able to use SSI, which is a good alternative. Do the same thing - save your menu as... let's say 'menu.txt' and add this where you want your menu :

<!--#include virtual="menu.txt" -->

I strongly recommend using one of these - php if possible.

I'd like a different image depending on the time of day...

whiskyI'm no php expert, but I've answered this question a couple of times recently, so I thought I'd put this up...

This code : PHP
<?php
$date = getdate();
$hour = $date['hours'];
if ($hour >= 7 && $hour <=14) {$pic='wine';} // 7am to 3pm show wine
if ($hour >= 15 && $hour <=22) {$pic='whisky';} // 3pm to 11pm show whisky
if ($hour >= 23 || $hour <=6) {$pic='beer';} // 11pm to 7am show beer
echo '<img class="fright" src="'.$pic.'.jpg" alt="'.$pic.'" />';
?>
... gives me the image (top right). My server is in Britain, so the times are based on British times. To use this, just save your page with a .php extension and stick the code in where you'd like your image (and of course change the image names and paths and the times).

How do you have something random - like a random background?

I think this is best done with PHP...

The code below - in the head of a page - gives us this page.

PHP
<?php
$images=array('wine.jpg','whisky.jpg','beer.jpg','whisky2.jpg','bg.gif','cbg.jpg');
$rand=rand(0,5);
$image=$images[$rand];
echo'<style type="text/css">
body {
background-image:url(images/'.$image.');
}
</style>';
?>

Here are a couple more examples of randomness...

And how about a set of rotating links, where one is an image?

Here's one way to do it.

How do you open a link in a new window?

Mark Kessell is an Australian-born physician who left medical practice to study art in New York where he now lives.

HTML
<a href="http://studiocyberia.com" onclick="return !window.open(this.href);">Mark Kessell</a>

How do you open two new windows?

You need a bit of javascript for this. Put this script in your head or add the function to your external .js file...

javascript
<script type="text/javascript">
function twoWindows (one,two) {
window.open(one);
window.open(two);
}
</script>

Your link would look something like this...

HTML
<a href="http://bonrouge.com" onclick="twoWindows('http://bonrouge.com','http://guardian.co.uk'); return false">bonrouge.com & The Guardian</a>

(Though I have no idea why you would want a link that opened this site and The Guardian at the same time.)

If javascript is disabled, the regular link will work and it will open up in the same window. (You won't see the second link, which is a shame as The Guardian is a fine newspaper).

Some select boxes go to a link when selected. How's that done?

Here's one way to do that:

HTML/javascript
<select onchange="window.location=this.value">
<option value="#n">...</option>
<option value="http://bonrouge.com">bonrouge</option>
<option value="http://google.com">Google</option>
<option value="http://prince.org">Prince</option>
</select>

Here:

How do you get the little icon in the browser's address bar?

The easiest way is to go here.

How can I test my site in IE5x browsers?

Download them.

I want to automatically re-direct users to my new address.

If you have php available - most commercial servers have php installed - you can replace your old index page with this :

PHP
<?php header("Location: http://mynewaddress.com"); ?>

Just that - nothing else. Put it on a blank page by itself and save it as 'index.php'. Upload it and remove any other index page.

(An easy way to check if you have php available is to do this and see if it works - if it doesn't, your old host was a bit crap, so well done for moving).

Alternatively, you could use an html meta refresh. With this, you can make the page re-direct after so many seconds, so if you want the user to know that the she is being redirected, then you could use this:

HTML
<meta http-equiv="refresh" content="5;URL=http://bonrouge.com/">

How do you set and read a cookie?

I would recommend using PHP.

Put this on a blank page, and save it as say 'biscuit.php':

PHP
<?php
$style=$_GET['cookievalue'];
setcookie ('cookiename', $cookievalue, time()+31536000, '/', 'mysite.com', '0');
header("Location: $HTTP_REFERER");
?>

Change the first, second and fifth values accordingly.

Then, on the page where you want the user to set the cookie, you basically put a link - either an actual href link or via a form.

Let's say to set the cookie the user will just click a link on your page. The link will look something like this :

HTML
<a href="biscuit.php?cookievalue=jesus">I really like Jesus</a>

Then the cookie 'cookiename' will be set with the value 'jesus' and the page will appear to refresh, as the last line of the php sends the user back to where she just came from.

Then, back on your page... You need to save your page with a .php extension too as this will read the cookie and print the necessary information...

Somewhere on your page (where you want the information to appear), you can put something like this:

PHP
<?php
if (!isset($_COOKIE['cookiename']) {
echo (($_COOKIE['cookiename']=="jesus")? '<a href="jesusstuff.htm">Read all about Jesus!</a>' : '');
}
?>

If the cookie will be set with a password, you'll change the $_GET in the 'biscuit.php' page to $_POST and... well, do something like this :

biscuit.php :

PHP
<?php
$style=$_POST['cookievalue'];
$pass=$_POST['pass'];
if ($pass=="bigjesuslover") {
setcookie ('cookiename', $cookievalue, time()+31536000, '/', 'mysite.com', '0');
}
header("Location: $HTTP_REFERER");
?>

yourpage.php :

HTML
<form action="biscuit.php" method="post">
<p><label>Password: <input name="pass" type="password" /></label></p>
<p><label>I want to know the good news!: <input name="cookevalue" type="checkbox" value="jesus" /></label></p>
</form>

So, that's one way to do it with PHP...

Quirksmode has a good article about javascript cookies if you'd rather do it that way. PHP is more reliable though - as long as youer server has PHP installed.

Comments

#1
2005-02-17 hitmann says :

Excellent page. Exactlty what I was looking for. Will be bookmarked once I get home.

#2
2005-02-17 BonRouge says :

Nice one! I've only written two questions and I've got great feedback already. Cool.

#3
2005-02-18 jlreich says :

I like it. Much easier to go throuugh than all the big tutorials. Kind of like a refresher course with tips and tricks.

Thanks.

#4
2005-05-20 Anuschka says :

Great, I have bookmarked this. You are targeting some problems that I took forever and a day to find out about - but I still can't get rid of the margin below my image, despite your advice. <:'( Bouhou, will read on...
Anuschka

#5
2005-05-20 BonRouge says :

Anuschka,
Can you contact me through my form? I'll see what I can do to help.

#6
2005-07-02 bulldogric says :

The SSI/PHP tip is excellent -- made my day!

Thank you! Bookmarked

#7
2005-07-04 Ness says :

Nice page, BonRouge !
I have one suggestion for the link on the whole div...

.blank {
width:100%;
height:100%;
border: none;
display:block;
}

and then :

<div><a class="blank" href="http://www.whatever.com"></div>

It works in all browsers... smile
and this is very usefull when you're making a whole css design...

But your page is great, I learnt lots of things !!!

#8
2005-07-07 BonRouge says :

D'oh! I've been asleep... I've just noticed these latest messages...

Wayne,
Yeah, I think I saw you post that on a forum somewhere. I think it's an interesting idea. I don't usually use objects so I hadn't thought of that.
Thanks for pointing out the problem in the link - I've fixed it now.

Ness,
I think I see a problem with your idea there. Usually, people put things inside divs - like paragraphs and things. You won't be able to put a paragraph inside your 'a' tags there for the same reason that you can't put a div inside inside 'a' tags... You just can't.

Thanks all for the positive comments. I hope to keep adding stuff here, so... you know - come back some time.

#9
2005-08-29 Silje says :

I love it! I love it!

very happy

http://www.unenlightened.com

#10
2005-08-31 Daniel K. Geren says :

How do I add my own question to the FAQ. For instance, How do I float a div to the right of an absolutely positioned div without having the absolutely positioned div disappear in IE? This works great in Firefox and Opera, by the way. But, I expect that about 90% of the people who see my site will use IE.

#11
2005-08-31 BonRouge says :

Daniel,
I'm afraid you don't add a question to the FAQ - this isn't a forum. For one thing, your question isn't a 'Frequently Asked Question'...
Contact me via my contact form and I'll see what I can do (don't write too much though as my form script is a bit dodgy and it sometimes gets screwed up - I've been meaning to fix it for ages, but I haven't had the time).

#12
2005-09-02 BonRouge says :

Now, I'm a bit concerned... Up there ^^^ it says Silje says :
I love it! I love it!
very happy

...and then there's a link to a page. Is this just spam? Is someone actually spamming this page? I checked the page and the author doesn't seem to have taken any notice of anything on this site.
So... 'To delete or not to delete? That is the question'.

#13
2005-11-09 Rutam says :

For a designer with little coding skills, your tut helped a hell lot! I just hope everyone else writing css tuts make an effort to make those a bit designer friendly ;)

#14
2005-11-16 css noob says :

Great page bonRouge! well written and easy to understand; now i can have proper footers.. woohoo!

css gurudom here i come!

#15
2005-11-16 BonRouge says :

Rutam / css noob,
Thanks for the positive feedback. There's more I want to add to this, but it's not easy to find the time.
I'm glad you find it easy to understand - that was my hope with this page. smile

#16
2005-11-16 Rutam says :

Keep up the good work smile already bookmarked this page for future ref. If you need any help with gfx/design do let me know; www.rutam.com

#17
2006-01-08 Dopple says :

Thanks for writing this. The part on IE doubling margins on floats was a great find. Thanks again.
*Bookmarked*

#18
2006-02-02 Lakio says :

I really like this page smile
Im a js fan and loved IE>css>expression and "return !window.open(this.href)" lol super

1. is IE>css>expression ok to use?
2. In "How do you make a whole div into a link?" why do you have "javascript:" in a onclick?
onclick="javascript:location='http://bonrouge.com'

#19
2006-02-03 BonRouge says :

Lakio,

1. Yes, but only in IE conditional comments - otherwise, it won't validate. It'll still work if it's in your regular stylesheet, but if validation's important to you, hide it.
2. I'm not sure to be honest... It's probably not necessary, eh?

#20
2006-03-08 blackartz says :

This the most useful list of things CSS I've found. I was looking for info about gaps beneath images and found half a dozen other things which have been doing my head in too!
Huge thanks for reducing my stress levels so neatly smile

#21
2006-03-18 tankedup says :

The php tips on menus was a real eye opener!
One question, I'm a bit of a novice on php, will the menu still be as search engine friendly as having <a href="" links on the page.
Sorry if that's a dumb question, as I said, I'm new to this.
Wish I'd found this site four months ago when I started, would have saved me loads of time smile

#22
2006-03-18 BonRouge says :

tankedup,
PHP, being a server-side language, includes whatever you want it to include before the page reaches the browser, so what you see in the browser is exactly the same as what a static html page shows. There is no SEO issue here.

#23
2006-04-24 Sheriff says :

This is by far one of the most informative pages regarding web development quick fixes on the internet. I have already bookmarked it and will inform many of my friends...thanks!

#24
2006-06-05 Chris says :

Excellent!!! Please keep adding!

#25
2006-06-06 BonRouge says :

Chris,
I will add more when I come across more things I consider to be 'frequently asked questions'... Right now, I can't think of any more.

#26
2006-07-31 Uncle Cheese says :

I hold this site almost entirely responsible for teaching me how simple CSS design can be. I continue to send both newbies and seasoned designers here every day. It's a great asset to the web building community. Thanks, Bon Rouge!

#27
2006-11-16 shannonlp says :

Thank you for an excellent page!! IE6 has been making me feel a little older over the last couple of days.

#28
2007-05-29 JohnMack says :

Thanks for the PHP tips mate. Saved my life, you have (or at least my weekends, which amounts to the same thing). Sooner or later I'd probably have stumbled upon the info somewhere, but it's great to be taught things sometimes, rather than just grope around in the dark hoping for a lucky break. Cheers!

#29
2007-06-20 Alex says :

On your "Why does my content shift to the left on some pages (in FF)?" section you have height: 100.1%; I prefer to use 100.01% as .1 can sometimes cause a very slight bit of scroll action still, whereas 100.01% doesn't ;-)

#30
2007-11-14 JohnnyW says :

Brilliant! Supremely useful, thanks!

#31
2007-11-30 Ugot2BkidNme says :

for a popup window I use the following code for accessibility reasons this makes keyboard navigation possible as well as works with and without Javascript.

<a href="http://www.google.com" target="myName" onclick="javascript:return !window.open(this.href,this.target,'your other values here');" onkeypress="this.click();">link here</a>

#32
2008-01-10 Rational Rabbit says :

Wow! A bunch of great tips here! You have managed to tap some very common and persistent problems that, for some reason, are hard to find good information on. Your explanations are clear and to-the-point. Kudos!

Comment form

Please type the word 'PHP' here:

BB code available :

  • [b]...[/b] : bold
  • [it]...[/it] : italic
  • [q]...[/q] : quote
  • [c]...[/c] : code
  • [url=...]...[/url] : url