Useful CSS snippets
author: mike foskett updated: 19th December 2008
A few useful snippets for style sheets. Not comprehensive but it will build over a period of time. I hope you find them useful too.
Firefox and Safari opacity issues
Author: mike foskett uploaded: 19th December 2008
After upgrading to Firefox 3 I found links in the resources list (right-hand column) behaved strangely. Link text turning white on rollover and locking on. The condition only cleared after scrolling off screen. Strange behaviour indeed.
The issue was caused by poor handling of the opacity property which was applied to the containing div. On investigation it appears both Firefox and Safari have various issues rendering opacity. The workaround? Never use a setting of 1 in either CSS or JavaScript. Instead use:
opacity:0.9999;
Printing preformatted (pre) content
Author: uploaded: 14th September 2008
Objects that are preformatted may go off page when printing. This may help:
pre {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
Full article: Making preformated <pre> text wrap in CSS3, Mozilla, Opera and IE.
Accessible image replacement
Author: mike foskett uploaded: 13th September 2008
Most image replacements are fine unless images are switched off. Then nothing is displayed.
The best method to replace text, in say a div, with a graphic.
<div>Content alt text<span></span></div>
And then the important bit:
div {
position:relative;
width:XXXpx; height:YYYpx;
font:1em/100% verdana,sans-serif
}
div span {
position:absolute;
top:0; left:0;
width:100%; height:100%;
background:url(headingImage.jpg) no-repeat
}
A slight varient is required if it's a link too:
<div><a href="#">Content alt text<span></span></a></div>
And the CSS:
div {
position:relative;
width:XXXpx; height:YYYpx;
font:1em/100% verdana,sans-serif
}
div * {
position:absolute;
top:0; left:0;
width:100%; height:100%;
display:block;
text-decoration:none;
cursor:pointer;
}
div span {background:url(image.jpg) no-repeat}
Now if CSS is disabled you get the text, screen readers get the text, and with images disabled you get the text. So remember to style the text too.
An online example of this technique may be seen on the Tesco Direct website
Please note that content images should be presented as an image in the HTML with adequate alt text.
CSS hacking IE
Author: mike foskett uploaded: 9th March 2008
So you need an inline hack for IE? The old underscore hack works well for IE before v7 but does not work for IEv7. Which can be useful in itself.
To get all IE browsers use * instead:
div {width:42.5em; *width:760px}
All versions of IE get width of 760px while other browsers get 42.5em.
div {width:42.5em; *width:760px; _width:50%;}
In this example IEv7 gets a width of 760px but IEv6 and older get 50%.
Method is untested in IEv8 which is supposedly more standards compliant.
Please note this is not the recommended method of styling IE, but it is useful for a quick fix for testing. The approved method would be to use conditional comments.
Using a single style sheet
Author: mike foskett uploaded: 6th July 2008
Reducing the number of files called by your html document (HTTP requests) improves the delivery speed of the page. Include all the print styles in the main style sheet. That makes one less file to fetch.
At the bottom of your main style sheet add the following:
@media print
{
...
}
Replace ... with all the print style properties.
Printing urls next to text links
Author: mike foskett uploaded: 9th March 2008
When printing a webpage links show as text which is pretty useless on a printed page. Here's a method to follow a link with the url when printing:
@media print
{
a:after {
content: " [" attr(href) "] ";
}
/* ... more print styles ... */
}
The @media print allows you to include print styles inside your normal style sheet.
This tip came from the excellent CSS tricks website.
Defining font-sizes
Author: mike foskett updated: 13th January 2008
The most accurate method to define a font size cross-browser, cross-platform is to use pixels. Unfortunately IE fails to scale fonts stated in pixels. Here's a workaround:
body {font:16px/1.4em verdana,helvetica,sans-serif}
* html body {font:100.01%/1.4em verdana,helvetica,sans-serif}
The method above supplies IE with font size stated in percentage while all other browsers are stated in pixels. In font-sizing terms 100% equates to 16px or 1em.
It is advisable to state the largest font size in the body element then scale down from there using em's, percentages, or keywords.
Update
The method fails in IEv7. The quick fix is to use the star hack:
body {font:16px/1.4em verdana,helvetica,sans-serif}
body {*font:100.01%/1.4em verdana,helvetica,sans-serif}
But personally I'm not happy with that and using a conditional comment seems excessive.
Skip to content links
Author: mike foskett updated: 13th January 2008
Skip to content links should be the first link on a web page and appear top left (for screen magnifiers). It is advisable to make the link visible at all times though some designs may prevent. If the link must be hidden then ensure it becomes visible when using the keyboard only. Here's a suggested method:
<div id="accessMenu">
<a accesskey="S" href="#content">Skip to content; Access key S</a>
</div>
Please ensure the id names make readable sense. One facility available to screen readers is to vocalise id names.
#accessMenu {position:absolute}
#accessMenu a {
position:absolute;
width:30em;
left:-200em
}
#accessMenu a:active,
#accessMenu a:focus {
position:absolute;
left:0;
top:0;
z-index:100;
color:red;
background:white
}
Consider keyboard users
Author: mike foskett updated: 13th January 2008
So you've added neat hover states to your links. Have you considered keyboard-only users? It is an important accessibility consideration to add active and focus states to all links.
a, a:link {color:blue; background:white}
a:visited {color:green}
a:active,
a:focus,
a:hover {color:red}
Active and focus states do not need to be the same as the hover state. Just made visually different and easy to see.
Styling JavaScript elements prior to page load
Added: 13th January 2008
If you use JavaScript to effect content styling in an accessible manner then it insists that the JavaScript is loaded prior to adding any associated styling. Otherwise, if JavaScript is not present, you could style elements in anticipation of scripting which never occurs.
For example consider a hidden div which is activated by a link via JavaScript. The div style would be display:none. If the style is applied before JavaScript loads, and then JavaScript is unavailable, the div will never be seen while the style sheet is on.
An accessible method insists the div be hidden by the JavaScript when loaded which is usually last. The effect is you get a flash of the un-styled div until the JavaScript has fully loaded. Not pretty but it's accessible.
The solution is simple, effective and grammatically correct. Add a style to the html element:
<script type="text/javascript">
/* <![CDATA[ */
document.documentElement.className="hasJS"
/* ]]> */
</script>
This should be applied to every page utilising HTML / CSS / JavaScript mix. It should be added straight after the title element in the head.
<title>The page title</title>
<script type="text/javascript">/*<![CDATA[*/document.documentElement.className="hasJS"/*]]>*/</script>
Now any content which changes when JavaScript is loaded can be fully styled in advance of page load.
From our previous example:
.hasJS div {display:none}
Will only hide the div if JavaScript is on. If it is on then it is hidden before the page is rendered preventing the flash of the un-styled div.
This solution came from an admired JavaScript programmer who I forgot to note. Usually I add a credit to the script but as this was a single line never included it. Very remiss of me. If it's your original please tell me and I'll add a full credit and link. I don't believe it was Chris Heilmann's version I saw first though.
The same method could be employed to target specific browser via testing for the user agent. Considered a bad practice but sometimes it may be of use.
Don't use capitalised words
Author: mike foskett updated: 13th January 2008
Unless they are abbreviations or acronyms. Some screen readers spell out the word so use CSS to do the task visually.
.capitalise {text-transform: capitalize}
Extreme font resizing in IE
Reworded: 28th July 2005
Use a percentage in the body element to prevent IE giving huge font-size steps when resizing. See the leveller.
IE refuses to copy or highlight content text
Added: 20th July 2005
An unusual effect. IE refused to copy or highlight body content text. The issue was related to the use of the base element in the head section. Without it, copy worked. With it, IE refused to highlight the text.
Example:
<base href="someURL" />
Caused issues. The solution was to replace it with:
<base href="someURL"></base>
Other head elements may also cause this problem, though the solution should be similar.
IE conditional comments
Updated: 13th September 2008
I recently needed to apply a tweak for IE v5 only. I resolved the issue by using conditional comments to supply a CSS repair file to IE v5 only.
The format is:
<!--[if "condition" IE "version number"]>
<p>Only IE displays this text if the condition is met</p>
<![endif]-->
There are 6 conditions that can be applied (there's a "logical not" case too):
- [if IE] - if above or equal to version 5
- [if IE 6] - if equal to version 6
- [if lt IE 6] - if less than version 6
- [if lte IE 6] - if less than or equal to version 6
- [if gt IE 6] - if greater than version 6
- [if gte IE 6] - if greater than or equal to version 6
The above will work on IE 7 and 8 too.
Valid version numbers are 5, 5.5, 6 and 7. Version 8 will follow suit. Though there is support for specific version numbers such as 5.0453
I found it very useful for adding a style for IE v5 only:
<!--[if IE 5]>
<style type="text/css">@import "IE5_only.css";</style>
<![endif]-->
Here's an example of targeting non-IE browsers:
<!--[if !IE]><!-->
<p>This is not Internet Explorer</p>
<!--<![endif]-->
Here's an example of targeting non-IE browsers and IE 7 or above:
<p>You are using
<!--[if gte IE 7]>
At least IE7 and not
<!-->
a non-IE browser
<!--<![endif]-->
</p>
Further information is available from Microsoft or search Google.
Validators do not check the code inside the comments so take care.
Since originally writing this snippet it has become the standard method for dealing with IE irregularities.
Accessibly replacing text with images
Added: 5th June 2005
There are quite a few methods to do this but here's one I used recently. It replaces the word "Correct" at the end of a sentence with a graphic tick.
In XHTML:
<p>This part of the text is displayed <span class="correct">Correct</span></p>
In CSS:
span.correct {background:url(tick.gif); margin-left:0.5em; text-indent:21px; position:absolute; overflow:hidden; width:20px; height:19px}
Which looks like:
This part of the text is displayed
The method is fine for end of line graphic replacement. Other methods are discussed on the mezzoblue website
Un-styled content flashing up in IE.
Recently reminded about this one. When using the @import method to attach a style sheet, IE will flash up the un-styled content before applying, that is if the style sheet isn't in the browsers cache.
The fix is easy. Ensure to follow the @import style link with a link or script. I tend to link to a print style so:
<style type="text/css" media="screen">@import "style.css";</style>
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
Access keys
Not CSS but it's here until a relevant section is created.
When referring to access keys as text always separate the words. It sounds funny in Jaws as a single word.
Converting pixel font-sizes to em's
To go from pixels to em's, simply divide by 16. Thanks to Alex James for that.
| Pixels | Points | Percentage | Ems |
|---|---|---|---|
| 9px | 7pt | 55% | 0.55em |
| 10px | 7.5pt | 62.5% | 0.625em |
| 11px | 8pt | 70% | 0.7em |
| 12px | 9pt | 75% | 0.75em |
| 13px | 10pt | 80% | 0.8em |
| 14px | 10.5pt | 87.5% | 0.875em |
| 15px | 11pt | 95% | 9.5em |
| 16px | 12pt | 100% | 1em |
Prevent centred designs jumping in Firefox
So you've a fixed width, centred design with a mixture of page lengths. Some fit inside the browser window while others don't. In IE this is no problem but in Firefox the vertical scrollbar only appears when the content is longer than the browser window, causing the design to jump left 10 pixels as the scrollbar appears.
A nasty unprofessional looking result. Here's a neat solution:
html {height:100%}
body {min-height:101%}
This forces Firefox and Netscape to consider the page to be larger than a screen full and adds the vertical scrollbar. No more content jumping. Thanks to SuziUK at webmasterworld for that one.
I found a min-height of 100.15% works sometimes, other times 102.5%. This is untested in Netscape, Opera or Safari. I suggest a little experimentation.
Mark Walsh [18th August 2005] suggests using this code instead:
body { overflow: -moz-scrollbars-vertical; }
And another which is a formally valid solution:
html { overflow-y: scroll; }
But doesn't work in all browsers
Style IE only
Invaluable in repairing the IE box-model. Any property that you wish only IE (<v7) to see add an underscore before the first letter.
#box {width:1000px; _width:800px; padding:100px}
_width is ignored by all browsers except IE (less than version 7).
The same effect can also be achieved using parent child selectors:
#box {width:800px; padding:100px}
html>body #box {width:1000px; padding:100px}
IE sees the first statement but does not understand html>body #box so it ignores it, while other more compliant browsers understand both.
Removing the fieldset border in Opera
Border:0 does not work in Opera but this does:
fieldset {border:0 solid}
The leveller (CSS reset)
Version one
The first style I use in a CSS file is a "leveller". The intention is to remove as many of the differences between browsers and platforms as possible in one fell swoop.
The code I use tends to change from time to time but here's the one used on this site:
body {background:#fff7dd; color:#006; font:76.1%/150% verdana, sans-serif}
body, h1, h2, h3, h4, h5, h6, p, div, form, code, pre, fieldset, legend, dl, dt, dd
{margin:0; padding:0; border:0}
/* ul,ol,li are treated on an individual basis */
Which was improved a little on my last project:
* {margin:0; padding:0}
html {height:100%}
body {
min-height:101%;
font:100.01%/130% Verdana, Helvetica, sans-serif;
color:#000; background:#fff;
width:760px; margin:0 auto
}
I've had to remove the border from the statement due to issues with Opera and input radios & checkboxes.
- * {margin:0; padding:0}
- Removes margin and padding from every element.
- html {height:100%}
- Sets the window height.
- min-height:101%;
- Sets the minimum page height to greater than the window height to force Netscape & Firefox to display vertical scrollbars, thereby preventing content jumping on fixed width pages.
- IE doesn't understand min-height and totally ignores this setting.
- font:100.01%/130% Verdana, Helvetica, sans-serif;
- Set font-size to a percentage preventing a Windows IE "extreme font re-sizing" bug.
- Set font-size slightly larger than 100% to repair Opera rounding errors.
- Set less than 101% to prevent Safari errors.
- The line-height setting gives nice, clear and easy-read spacing.
- Verdana is the most readable, and readily available screen font in Windows.
- Helvetica most readable, and readily available screen font on Macintosh computers.
- Sans-serif is the most readable to the widest audience for body text.
- color:#000; background:#fff;
- Set general colour & background.
- width:760px;
- Fixed width set for 800 pixel wide browser displays.
- margin:0 auto
- Margins are set for centring the content. This works for IE6, Firefox, Opera, Safari and Netscape but IE5 and IE5.5 require further treatment.
Leveller update
On my next project I'm trying this out for the first time:
* {margin:0; padding:0}
html {height:100%; font-size:100.01%}
body {
min-height:101%;
font:100.01%/130% Verdana, Helvetica, sans-serif;
color:#000; background:#fff;
}
Leveller version 3
Added: 21st June 2005
Further treatment for a centred design considering IE v5.0. Perhaps it's time this section became an article in it's own right?
* {margin:0; padding:0}
html {height:100%; font-size:100.01%}
body {
text-align:center;
min-height:101%;
font:100.01%/130% Verdana, Helvetica, sans-serif;
color:#000; background:#fff;
width:760px; margin:0 auto
}
body * {text-align:left}
#wrapper {width:760px}
Those additions:
- text-align:center
- Added to the body element to force IE to centre all content
- body * {text-align:left}
- Resets all text aligns to the left
- #wrapper {width:760px}
- States the wrapper width. All centred content goes inside a div with an id="wrapper.
Experimental reset
Added: 9th March 2008
An experimental reset was applied to this site:
html {
border:0 solid;
min-height:101%;
}
html * {
border:0 solid;
padding:0;
margin:0;
}
body {
position:relative;
color:#000; background:#f6f7f9;
font:16px/1.4em verdana,helvetica,sans-serif;
}
* html body {
font:100.01%/1.4em verdana,helvetica,sans-serif;
}
What's with the font statement? See Define font sizes above.
Further discussions on global resets are available on the Perishable Press website
Font-sizing em versus %
Personally for time-honoured reasons I use percents. Though provided the body font-size is stated as a percent then there is no reason to not use ems (unless you're supporting ancient browsers).
Hiding a complete style from Macintosh IE
This ones very useful if you're positioning elements.
/* Only IEv5 on a Mac ignores the next style rule because of this backslash \ */
.container {margin-top:-200px}
Hiding a style sheet from older browsers
Hides from Internet Explorer v4 and Netscape v4 on Mac and PC.
@import "styles.css";
Please note the white-space, and quotes, used do make a difference.
This one hides the style sheet from all Internet Explorer versions prior to v5.5 and the dreaded Netscape v4 series on both Mac and PC.
@import"styles.css";
Note no white-space and double quotes
A comprehensive list of hiding techniques may be found on the Dithered website.