CSS is a wonderful language for presenting web
pages. It’s not too difficult to learn, though like most things, it does
have a learning curve. Where many people seem to get tripped up is in
specific solutions to specific problems. Fortunately there’s a good
chance that someone before you has already had the same problem and even
better has found a solution.
Here are 47 of those solutions.
47 CSS Tips, Tricks, and Techniques to add to your CSS toolbox.
Some you may be familiar with while others may be new to you. The tips
below span from beginner to more advanced CSS code. Hopefully you’ll
find a few techniques that will be both new and useful to you and
perhaps some will find their way into your next project.
For those, who don’t know what is
CSS? And what it
can do? Than CSS (Cascading Style Sheets) is a style sheet language used
to describe the presentation semantics (that is, the look and
formatting) of a document written in a markup language. Its most common
application is to style web pages written in HTML and XHTML, but the
language can be applied to any kind of XML document, including SVG and
XUL.
Please follow the link below for detail introduction.
CSS always plays a vital role in web design and it always gives you
opportunity to make your website user friendly. Unfortunately, there is
no well defined way for you to find out about visitors thinking towards
your blog or its design. It’s always essential to play safe and give
others what they like using creative solutions. CSS isn’t always easy to
deal with. Over the last many years web-designers and developers have
written many articles about CSS and developed many useful tips and
techniques, which can save you a lot of time – of course, if you are
able to find them in time. That is the only reason why we created this
article to give you as many as CSS tricks in a single place.
CSS Tips, Tricks, and Techniques for Your Website
If you’re working with WordPress then of course, the
WordPress Codex
is always the best place to learn about WordPress and its tweaks with
CSS. However, if you are into web designing business than there are
thousands of resources available for CSS tips. But unfortunately, it’s
too much for a simple user. This the only reason we compiled this fairly
comprehensive list of the
47 Exceptional CSS Tips, Tricks, and Techniques to unleash the power of your favorite mark-up language.
Most of these tips what follows will work cross-browser. Where there
are differences between browsers alternate solutions have been provided
if they exist. With that said let’s dive in.
01. Horizontal Centering
To
horizontally center block level elements in CSS
you need three things. You need to explicitly set a width on the
element, set the left and right margins to auto, and include a
proper doctype to keep older versions of IE from going into quirks mode.
1 | div#page { width : 960px ; margin : 0 auto } |
The above will center the div with an id of page inside it’s parent container.
02. Vertical Centering Text with Line-Height
If you want to vertically center text within a containing block who’s
height is fixed, simply set the line-height of the text to be the same
as the height of the containing block
The HTML:
1 | < div id = "container" >some text here</ div > |
The CSS:
1 | div#container { height : 35px ; line-height : 35px } |
03. Vertical Centering Block Level Elements
Positioning can be used to
vertically center block level elements.
The HTML:
1 | < div id = "content" >your content here</ div > |
The CSS:
1 | div#content { position : absolute ; top : 50% ; height : 500px ; margin-top : -250px } |
The top left corner of the div will be positioned 50% from the top.
Since we want the center of the div to be positioned 50% from the top
you need to set a negative top margin equal to half the height of the
div.
This same trick works for horizontal centering as well. Change top to
left and margin-top to margin-left and set the negative margin to be
half of the width of the element.
1 | div#content { position : absolute ; top : 50% ; left : 50% ; width : 800px ; height : 500px ; margin-left : -400px ; margin-top : -250px } |
The above CSS will center the element both vertically and horizontally.
04. Fluid Images
To create
fluid images set a max-width on the images to be 100%
Unfortunately IE doesn’t do max-width. However IE treats the width property as though it was max-width. For IE use a
conditional comment and set
For a more details about creating fluid images in older versions of IE click the link above.
05. 3D Buttons with CSS Only
3D CSS buttons
are easy to create. The trick is to give your elements borders with
different colors. Lighter where the light source shines and darker where
it doesn’t.
1 | div#button { background : #888 ; border : 1px solid ; border-color : #999 #777 #777 #999 } |
The CSS above will create a button with the light source at the upper
left. Usually one or two shades of color change is all that’s needed,
but you can experiment for different effects.
06. CSS Font Shorthand
When using
shorthand on the font property you need to specify each property in the following order
1 | body { font : font-style font-variant font-weight font-size line-height font-family; } |
You don’t need to include every property, but know that for any you don’t include that property will be reset to it’s default.
07. Setting Multiple Classes on an HTML Element
Easy and easy to forget the proper syntax. If you want to set multiple classes on an html element it should look like:
1 | < div class = "class-1 class-2 class-3" > |
with all class names inside the same set of double quotes with a
space between each. The CSS specificity is controlled by the order of
the classes in your CSS file. If your CSS has:
then text inside the div will be red as class-1 is the last declared
in the CSS. The order the classes appear in the html is irrelevant.
08. Rounded Corners
When CSS3 is fully supported across browsers rounded corners will be as simple as:
1 | .element {border-radius: 5px } |
which will set a 5px radius on all 4 corners. For now we need some
browser specific CSS combined with a little JavaScript to make this work
in all browsers.
In Safari, Chrome, and other webkit browsers we use
-webkit-border-radius
and in Firefox and other Mozilla based browsers we use
-moz-border-radius
.
3 | -webkit-border-radius: 5px |
4 | -moz-border-radius: 5px |
Webkit and Mozilla use different syntax when specifying one corner.
2 | border-top-left-radius: 5px |
3 | -webkit-border-top-left-radius: 5px |
4 | -moz-border-radius-top- left |
For non Webkit and Mozilla browsers a little
jQuery plugin will mimic the border-radius property.
1 | $( ".element" ).corner( "5px" ); |
The jQuery corner plugin allows for more than setting the radius of
the corner. You can also set the corner to show as a number of other
patterns.
09. Link Style Order
When setting CSS on the different link states, the link states need to be set in a particular order
An easy way to remember is LoVe HAte. LVHA – Link, Visited, Hover, Active.
10. Clearing and Containing Floats
There are two basic methods to clearing
CSS floats. The first is to use the clear property
3 | < div id = "content" ></ div > |
4 | < div id = "sidebar" ></ div > |
Say in the above html you have your content and sidebar div floated
to the left and you want to ensure the footer div sits below both. You
would use the clear property
You could also use clear: left or clear: right depending on which way the content and sidebar are floated.
If on the other hand your html was:
2 | < img id = "logo" src = "" alt = "" > |
and both the logo and tagline are floated, your header div will
collapse and show as having 0 height. You can either add an empty
div
(
<div class="clear"></div>
) and then clear the empty div as above or you can use the overflow property on the header div to contain the floated elements
1 | div#header { overflow : hidden } |
The above will keep the header div from collapsing even if everything inside has been floated.
11. Conditional Comments
Conditional comments
are an ideal way to target IE browsers only, since IE is often the
browser that won’t cooperate. The basic form of a conditional comments
is:
The above will load an IE specific stylesheet only when the browser
viewing the page is Internet Explorer. You can further target specific
versions of IE.
You can specify any version of Internet Explorer and through a
combination of conditional comments you can server different CSS styles
to different versions of IE.
12. HTML Hack for IE
Another way to target IE specifically is to use the
HTML * hack.
Internet Explorer allows you to use something other than the html
element as the root of your document. By placing an * in front of html
in your CSS (
*html
) you can target IE only as other browsers will ignore the declaration.
1 | div#content { width : 580px } |
2 | * html body div#content { width : 600px } |
IE will use 600px for the width of the content div, while other browsers use 580px.
The above works for IE6 and below. When not in standards mode, but in
quirks mode this will work on IE7 as well. You can also target IE7 (in
quirks mode) specifically with
1 | *+html body div#content { width : 620px } |
13. CSS Specificity
When two or more CSS selectors are sending conflicting instructions
to a single html element, a choice must be made as to which styles to
apply. This is done through
CSS specificity calculations and is expressed in the form of (a.b,c,d)
1 | Element, Pseudo Element: d = 1 – ( 0 , 0 , 0 , 1 ) |
2 | Class, Pseudo class, Attribute: c = 1 – ( 0 , 0 , 1 , 0 ) |
4 | Inline Style: a = 1 – ( 1 , 0 , 0 , 0 ) |
In the following examples the specificity increases as you move down
1 | p: 1 element – ( 0 , 0 , 0 , 1 ) |
2 | div: 1 element – ( 0 , 0 , 0 , 1 ) |
3 | #sidebar: 1 id – ( 0 , 1 , 0 , 0 ) |
4 | div#sidebar: 1 element, 1 id – ( 0 , 1 , 0 , 1 ) |
5 | div#sidebar p: 2 elements, 1 id – ( 0 , 1 , 0 , 2 ) |
6 | div#sidebar p.bio: 2 elements, 1 class, 1 id – ( 0 , 1 , 1 , 2 ) |
14. min-height fix for IE
Sadly IE still doesn’t comply with
min-height
. However it does treat the height property as though it was
min-height
. Knowing that, we can sort of get
min-height
working in Internet Explorer.
3 | height : auto !important |
The first line above sets the min-height for non-IE browsers. The
last line essentially sets min-height in IE as IE will treat height as
we expect it to treat min-height. The middle line above is to ensure
that non-IE browsers don’t use 500px as the height of the element. Using
!important
will override the height declaration below in all browsers, except IE.
Another way to target IE only is to use _height. Only IE6 will treat
_height
as height. All other browsers will ignore it. You have to specify
_height
after any height declaration as IE will use whichever comes last.
15. Base Font-Size
Using fluid measurements like
'em' or %
on your fonts is
a great way to help create more fluid designs. It can be a pain though
to calculate ‘em’s for every different element. A simple trick is to set
your base font to be the equivalent of 10px. Since the default
font-size of browsers is 16px you can set a base
font-size
with the following:
Now if you want your h1 to be 24 px the calculation is much easier
16. 100% Height
100% height
is one of those things CSS doesn’t do so easily. When you specify an
element to have a height of 100%, the 100% refers to the containing
element’s height. The containing element would then need to be 100% the
height of its containing element and so on. The trick is to set the
height of the outermost elements to be 100%
1 | html, body { height : 100% } |
We need to add one more thing. If your content exceeds 100% height
then it will overflow its container. To correct this we’d need to set
min-height
on the content’s container
1 | #content { min-height : 100% } |
You can use one of the methods above for serving
min-height
to IE.
17. CSS Drop Caps
Drop Caps can easily be styled by taking advantage of the CSS pseudo-element
:first-letter
.
8 | font-family : Helvetica ; |
This should work in all modern browsers. CSS3 introduces the
::first-letter notation
to distinguish between pseudo-elements and pseudo-classes, but this new
notation is not yet compatible with IE. For now use the single
:first-letter
notation.
18. Remove Dotted Outline on Links
Easy with the CSS outline property
1 | a { outline : none } or a { outline : 0 } |
The outline is useful for accessibility so think twice before turning
it off completely. You may only want to set it for one of the specific
link states mentioned above.
19. Text-transform
Through the
CSS text-transform property you can make sure certain blocks of text are either uppercase, lowercase, or only the first letter of each word is uppercase
1 | p { text-transform : uppercase } |
2 | p { text-transform : lowercase } |
3 | p { text-transform : capitalize } |
20. Font Variant
Another trick with type is to use the font-variant property to create small caps
1 | p { font-variant : small-caps } |
If the font you’re working with doesn’t have a small caps variation,
know you’ll be creating pseudo small caps, which may or may not look as
good as you’d like.
21. Removing the Border from Image Links
By default any image that is wrapped in a link will have a border
around the image (similar to the way text is underlined). Removing the
border is simple
1 | a image { border : none } or a image { border : 0 } |
Since I never want to see the border around image links I usually set the above on every site I develop.
22. Using a CSS Reset for Cross-Browser Compatibility
One of the issues in
cross-browser web development
is that different browsers use different default values for various CSS
properties. By explicitly setting a property like margin to be 0 for
certain html elements we can assure that the margin will be 0 on that
element in all browsers.
The best way to do that is to use a CSS reset file like the ones developed by
Eric Meyer or
Yahoo or you can develop your own.
Using a CSS reset ensure that all browsers are on the same page so to speak.
23. Setting Padding on Background Images
Since background images don’t create a new
CSS box
you can’t directly set padding on them. What you want to do is use the
background-position property on the background image to create the same
effect.
1 | background-position {top-value left-value} |
Top values can be top, center, or bottom and Left values can be left, center, or bottom
Both can also take values in % or px or any other measurement. So to
create 5px of padding around a background image you would use:
1 | { background-position : 5px 5px } |
24. Stretching a Background Image
To create a background image that can expand and contract with it’s
containing element you want to create an image larger than needed, large
enough to accommodate the largest possible size of the containing
element. Then use the background-position property to center the
background image
1 | { background-position : 50% 50% } |
The above will center your background image in the containing
element. The image will grow and shrink to fit the size of the
containing element and always be centered. You’ll want to make sure the
center of the image contains the most important part of the image since
only the center is guaranteed to visibly show.
25. Wrap Links Around a Background Image
Again since a background image doesn’t create a new
CSS box
you can’t directly wrap a link around it. You can either wrap the link
around the containing element or wrap the link around all the content
inside the containing element.
Either of the above will essentially let someone click your background image as though it were a link.
26. Background Images as List Bullets
Sometimes it’s nice to be able to use an
image as a bullet instead of one of the supported
list-style-types
.
3 | background-image : url ( "path-to-your-image" ); |
4 | background-repeat : none ; |
5 | background-position : 0 0.5em ; |
27. Swap Background Images on Hover
There are two very similar ways to achieve this. The key in both is to use the
:hover pseudo-class
to change either the url of the image or the position of an image sprite
1 | .element { background-image : url ( "path-to-an-image" )} |
2 | .element:hover { background-image : url ( "path-to-a-different-image" )} |
4 | .element { background-position : top-value left-value} |
5 | .element:hover { background-position : different-top-value different-left-value} |
Unfortunately IE only accepts :hover on a link and not another element. You can use something like the
suckerfish system to dynamically add a class for IE and simulate the :hover behavior.
28. Visibility or Display?
On the surface both the
CSS visibility and display properties seem to do the same thing, hide or show an element on the page. Beneath the surface they work differently.
{visibility: hidden}
– The element holds the space, but isn’t seen
{display: none}
– The element does not hold space. Other elements collapse to fill the space
Most of the time you likely want to use
display: none
, unless your goal is to leave an empty open space on your page.
29. Cross-Browser Transparency
Not all browsers currently support the CSS3 opacity property. However we can still make transparency work across browsers.
2 | filter:alpha(opacity= 50 ); |
From the bottom up:
opacity is the CSS standard and will work in current Webkit and Mozilla browsers as well as Opera
-moz-opacity is
for older versions of Mozilla Browsers
-khtml-opacity
is for older versions of Safari and any browser using the khtml rendering engine
filter:alpha(opacity=50)
is for Internet Explorer
30. Target IE7 (and below) and IE6 (specifically) without Conditional Comments
We all know how difficult IE can sometimes be when it comes to CSS.
However instead of cursing IE under your breath or out loud you can
easily write IE specific code that other browsers will ignore. My own
preference is for conditional comments, but here’s a quick trick you can
use in your main CSS file.
With the exception of IE, all browsers will ignore the asterisk in
front of the property. Everything other than IE6 will ignore the
underscore. The order of the above properties is very important due to
CSS precedence rules.
31. nth-child
The
nth-child
CSS pseudo-selectors allow you to target the 3rd or 7th or nth element
in a list. Another use would be to style odd and even rows in a table
differently. The alternative is to add a class specifically to the
list-item you want to style differently, but that’s not very flexible.
The nth-child syntax looks like this:
The above would select the 3rd item in the list and give it a blue background
Similarly the code above would style every 3rd list item with a blue background
Unfortunately no current version of IE supports it. However there is a way to
simulate the 1st bit of code above for IE7 and IE8.
1 | ul > li:nth-child( 3 ) is the same as ul > *:first-child + * + * |
The code above will also target the 3rd element in the list in a way
that IE7 and 8 understand. Not quite as useful as being able to use
(3n+3) to target every 3rd list-item, but better than nothing.
Hopefully IE9 will support nth-child.
Another and perhaps more practical solution currently is to use jQuery, which supports all CSS3 selectors.
32. Basic 2-column CSS layout (fixed width, centered, header and footer, sidebar on right)
The above is a pretty common website layout and it’s rather easy to code.
The HTML:
The CSS:
1 | #wrapper { width : 960px ; margin : 0 auto } |
2 | #content { float : left ; width : 600px } |
3 | #sidebar { float : left ; width : 360px } |
The specific widths are arbitrary, but it is necessary to include a
width. The keys are centering the wrapper as described above in this
post, floating both columns, and clearing the footer div. You could also
float the sidebar div to the right. Either will work, though I find it
easier to float both in the same direction.
33. Basic 3-column CSS layout (fixed width, centered, header and footer, sidebars on right and left of the content)
Expanding on the above 2-column layout is this common 3-column layout.
The HTML:
The CSS:
1 | #wrapper { width : 960px ; margin : 0 auto } |
2 | #primary { float : left ; width : 230px } |
3 | #content { float : left ; width : 500px } |
4 | #secondary { float : left ; width : 230px } |
Again the widths are arbitrary, but necessary. You can float the secondary div to the right if you prefer.
34. CSS Triangles and Other Shapes
CSS borders come together at an angle at any corner. This isn’t
obvious when setting a border that’s the same color on all sides or if
your
border-width
is only a few px. Making the width much
larger and setting different border-colors on different sides lets you
see this clearly. Taking advantage of these angles we can use the
border-property to
create some interesting shapes.
Creating a triangle
is a matter of setting the border-color on 3 of the 4 sides to
transparent. You also want to set the width and height of the element to
be 0 in order for all 4 corners to meet at a point. You can set the
border opposite the triangle to 0 as well, but the adjacent borders need
to maintain a width or the entire element with borders will collapse to
a single point.
The HTML:
1 | < div class = "triangle" ></ div > |
The CSS:
2 | border-color : transparent transparent green transparent ; |
4 | border-width : 0px 300px 300px 300px ; |
With a little experimentation you can create moe interesting shapes, especially if you combine several elements.
35. Prevent a Line Break
Sometimes the text in a link or heading will break where you don’t want it to. A simple way to prevent this is:
1 | h 1 { white-space : nowrap ; } |
36. Class vs. Id
Use an Id for elements that are used once and only once on a page
The HTML:
1 | < div id = "content" ></ div > |
The CSS:
1 | #content { background : #fff } |
Use a class for elements that may be reused on the page
The HTML:
The CSS:
1 | .large-text { font-size : 1.4em } |
37. Replace Text with an Image
Better typography through more font choices is here, but there are
still limitations to using it in practice. Sometimes the easiest
solution is to use an image. However you also want the original text to
be there for search engines and screen readers. A simple way to have
both text and image is to use the
text-indent
property.
3 | background : url ( "h1-image.jpg" ) no-repeat ; |
The height and width should match those of your image
38. Style the Element that has Focus in a Form
A nice usability tip is to let people filling out a form know which input currently has focus. You can do this easily using the
:focus pseudo-selector
1 | input:focus { border : 2px solid green ; } |
This way your users will know exactly which field is ready for input
39. Understanding !important
!important is a way to override
CSS specificity.
In general it’s not the best solution since the more you use it, the
more you end up needing to use it again. It can make your CSS
unmaintainable in a hurry. It can be useful due to a quirk in IE. When
you have something like the following
browsers should show the h1 with a color red. IE, however will show
the style that comes last instead of following the rules of precedence.
So the above code would show your h1 as red in all browsers except IE
where the color would be blue.
40. Simple Debugging in CSS
Sometimes your CSS doesn’t seem to be working like you expect and you
want to isolate one element in your html to see what space it occupied.
An easy way to do this is to give the element a border temporarily
1 | .element { border : 1px solid red } |
One downside of the above is the extra px in the border could
temporarily throw your layout out of whack, since it increases the width
of your element. You may find at times it drops a floated element
further down the page for example. Still it can be a quick and easy way
to see what’s going on and you can overcome the width limitation, by
temporarily decreasing the width you’ve given to the element to
compensate for the extra width the border adds.
41. Create a CSS Frame for Images
Many images look nice a frame. You typically frame pictures before hanging them on a wall so why not
add a frame to images on your website. Just like what you can see how every article image here at
instantShift is framed using modified verion of this very same trick.
The trick is to wrap your images in a div and add a simple class.
The HTML:
1 | < div class = "frame" >< img src = "" alt = "" height = "" width = "" ></ div > |
The CSS:
2 | border : 2px ridge #000 ; |
4 | background-color : #fff ; |
8 | border : 2px solid #ooo; |
You can use a variety of border-style values to create different
looks to the frame (groove, ridge, inset, outset, double, dotted,
dashed, solid). The padding and background-color on the frame div will
create the look of a mat around your image. Adding border, padding, and
margin to the image itself can create the effect of having a second mat
around your image for an extra effect.
Once set up all you’ll need to do to add your frame to any image is
wrap it with a div and assign the class. You can even create several
different styles of frames and then pick and choose which to use for
each image.
42. Mobile Specific Stylesheets
As more and more people are accessing the web via smart phones and
other mobile devices we need to make sure our sites display well on
different platforms. Fortunately html allows you to
serve different stylesheets for mobile devices.
1 | < link type = "text/css" rel = "stylesheet" href = "handheldstyle.css" media = "handheld" > |
43. Letterpress Type Through CSS
The basic idea is to make use of the CSS3 property for
text-shadow to create the letterpress effect.
3 | text-shadow : 0px 2px 3px #555 ; |
The trick is to use a shadow color that’s lighter than the text color
and offset it a little and add a bit of blur. The values above for the
text-shadow property are:
1 | text-shadow : x-offset y-offset blur color; |
44. Setting Page Breaks For Print
Some people will want to print your pages and you may want your pages
to print in a more readable form. For example you may have a table of
data on a page and you’d prefer the entire table be printed on one page
as opposed half the table ending up at the bottom of one page and the
other half at the top of the next. CSS offers a way to force a
page break in some places and prohibit in it others.
First you’ll need to direct your styles to printed media through @media print
3 | table {page-break-inside: avoid} |
The above will tell printers to do what they can not to break the
table over two pages. CSS provides a total of 3 properties related to
printed page breaks. Possible values in parenthesis.
page-break-before
(auto, always, avoid, left, right, inherit)
page-break-after
(auto, always, avoid, left, right, inherit)
page-break-inside
(auto, avoid, inherit)
45. Creating Circles With Border-Radius
The CSS2 border-radius property can be used to create circles in all
browsers that support the property. The trick is to set the height and
width of the element so they’re the same and set the border-radius of
the element to be half that value.
6 | -moz-border-radius: 150px ; |
7 | -webkit-border-radius: 150px ; |
border-radius is the CSS standard property
-moz-border-radius
is for Mozilla based browsers like Firefox
-webkit-border-radius
is for webkit based browsers like Safari and Chrome
Unfortunately none of the above will work in any current version of Internet Explorer.
46. CSS Tooltips
You can create a lightweight CSS cross browser tooltip easily with a few lines of code.
The HTML:
1 | This is the < a class = "tooltip" href = "#" >Tooltip Link< span >This will be the text that shows up in the tooltip</ span ></ a > You can place any text you want here. |
The CSS:
1 | a.tooltip { position : relative } |
2 | a.tooltip span { display : none ; padding : 5px ; width : 200px ;} |
3 | a:hover { background : #fff ;} |
4 | a.tooltip:hover span{ display : inline ; position : absolute ;} |
You can add more styles to the above to suit your design. The key is the span is set to
display: none
until you hover over the link. When you hover over the link the display
is changed to show inline and given a position of absolute. position:
relative is necessary on the link in order to ensure the tooltip is
positioned in relation to the link and not another containing element.
47. Creating a Fixed Header
Instead of letting your entire page scroll you might want to hold the header with your logo and navigation fixed in place and
only let the content below scroll.
The HTML:
1 | < div id = "header" >header </ div > |
2 | < div id = "content" >content </ div > |
The CSS:
You want to make sure to keep the header and content divs separate and then use
position: fixed
on the header. Other ideas you can try are
creating a scrollable table with a fixed header within your page or keeping both
header and footer fixed while allowing your content to scroll between them.
Further Resources
Other Resources
from http://www.instantshift.com/2010/03/15/47-css-tips-tricks-to-take-your-site-to-the-next-level/