Let’s gather our knowledge

5 tips for writing better CSS

True, anyone can write CSS. Even programs are doing it for you now. But is the CSS any good? Here are 5 tips to start improving yours.

In this article I want to talk about 10 different tips you can write proper and clean css code as well as to start improving yours, as quickly and efficiently as possible.

1. Start with a CSS Reset

Seriously, always use a reset of some sort. Whether you are using the Eric Meyer Reset, the YUI Reset, or your own custom reset, or my reset css ;) just use something. It can be as simple as removing the margin and padding from all elements:

* { margin: 0; padding: 0; } 
html, body, div, span, p, form, label, fieldset, legend, table, caption, tbody, tfoot, thead, tr, th, td h1, h2, h3, h4, h5, h6, dl, dt, dd, ol, ul, li, a, applet, object, iframe, blockquote, pre, abbr, acronym, address, big, cite, code, del, dfn, font, img, ins, kbd, q, s, samp, small, strike, sub, sup, tt, var, strong, em, {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-weight: inherit;
font-style: inherit;
font-size: 100%;
text-align: left;
vertical-align: baseline;
font:Tahoma, Times, serif;
body {line-height:1.5;}
ol, ul {list-style: none;}

2. Comments your CSS block

You should keeping organize your stylesheet clean and easy to read, comments are going to be a great way for you to keep things structured and clean. By commenting out blocks of code. For example, this is how I structure my stylesheets:

Remove margin and padding from elements  
/*****Basic Elements*****/  
Define styles for basic elements: body, h1-h6, ul, ol, a, p, etc.  
/*****Generic Classes*****/  
Define styles for simple things like floating to the sides, removing a bottombottom margin on elements, etc  
Yes, these may not be as semantic as we would all like, but they are necessary for coding efficiently   
/*****Basic Layout*****/  
Define the basic template: header, footer, etc. Elements that help to define the basic layout of the site  
Define all elements in the header  
Define all elements in the content area  
Define all elements in the footer  
Continue to define the other sections one by one  

3. Use Useful Naming Conventions

Name your elements based on what they are, not what they look like. For example, .xyzPart is much less versatile than .commentPart, and .postContent is more limiting than .header.

4.Stay consistant

Whatever way you decide to code, stick with it. I am sick and tired of the whole 1 line vs. multiple lines for your CSS debate. There is no debate! Everyone has their own opinion, so pick what works for you and stick with it throughout the stylesheet. Personally, I use a combination of both. If a selector is going to have more than 3 properties, I break it to multiple lines:

div.header { float: left; width: 100%; }  
div.header div.column { border-right: 1px solid #ccc; float: rightright; margin-right: 50px; padding: 10px; width: 300px; }  
div.header h1 { float: left; position: relative; width: 250px; } 

It works for me because 3 properties is about what fits on 1 line in my text editor before wrapping to another line. So just figure out what works for you and be consistent.

5. Don’t Repeat Yourself

Re-use attributes whenever possible by grouping elements instead of declaring the styles again. If your h1 and h2 elements both use the same font size, color and margins, group them using a comma.

h1, h2{
margin-top: 10px; 
margin-right: 30px;
margin-bottom: 14px; 
margin-left: 15px;
color: #FFFFFF;
font-family: Arial;
font-size: 12px;
font-weight: bold; 

much moreefficient than this

margin-top: 10px; 
margin-right: 30px;
margin-bottom: 14px; 
margin-left: 15px;
color: #FFFFFF;
font-family: Arial;
font-size: 12px;
font-weight: bold; 

margin-top: 10px; 
margin-right: 30px;
margin-bottom: 14px; 
margin-left: 15px;
color: #FFFFFF;
font-family: Arial;
font-size: 12px;
font-weight: bold; 

You should also make use of shortcuts whenever possible. Always be on the lookout for opportunities to group elements and use declaration shortcuts.
You can accomplish all of this:

margin-top: 10px; 
margin-right: 30px;
margin-bottom: 14px; 
margin-left: 15px;
font-family: Arial;
font-size: 12px;
font-weight: bold; 

with only this

margin: 10px 30px 15px 15px; 
font: bold 12px Arial;

It’s very important that you understand the order in which CSS interprets these shortcuts: top, right, bottom, left. A big clockwise circle, starting at noon.

1. It’s critical when working with CSS to be aware of the various properties at your disposal and how to use them correctly.

2. Using a good editor can increase productivity. Syntax highlighting and auto-complete functionality (plus validation and code references) make life easy. Check out Notepad++, Coda, and don’t discount Dreamweaver CS’s code view until you try it.

3. In many ways, experimentation is the mother of innovation. Give yourself time to play; trial and error will help you learn and memorize techniques quickly. Check out these CSS3 experiments, for inspiration: How to Create Inset Typography with CSS3, Semantic CSS3 Lightboxes, and 10 Interesting CSS3 Experiments and Demos.

4. Enable Gzip compression server-side whenever possible; it shrinks the size of files such as CSS and JavaScript without removing any of the content.

5. Caching will conserve bandwidth for visitors and account for much faster speeds. Take advantage of it whenever you can. Learn about optimizing browser caching.

6. Whitespace is important for CSS readability. Using whitespace to format your stylesheet adds bytes to the file size, but it’s made up for in increased readability.

7. Avoid using inline code (in either elements using the style attribute or in the HTML document within <style> tags), and put them instead in your external stylesheets. It’ll be easier to maintain and also takes advantage of browser caching.

8. Whatever method you use to lay code out, be consistent. You’ll avoid potential problems such as misinterpretation.

9. Conditional comments can help you target versions of Internet Explorer for style. Filtering vendor-specific code isn’t ideal, and comments are safer than ugly hacks.

10. This tip is slightly controversial, but I recommend using a single stylesheet rather than multiple ones. It reduces the number of HTTP requests and improves maintainability, giving your site a performance gain. This is a tip supported by Google Page Speed guidelines.

11. When there are conflicting style rules, style rules that are later down the stylesheet supersedes the ones that come before it. Thus, put mission-critical declarations at the end, where they won’t be in danger of being overridden by other styles.

12. If you encounter a bug and can’t determine its cause, disable CSS (using something like Firebug or the Web Developer add-on) or simply comment out all of the styles, and then bring selectors back one by one until the fault is replicated (and thus identified).

13. Make sure your code works in various browsers. Check it against the latest versions of the top five: Internet Explorer, Firefox, Chrome, Safari and Opera.

14. Additionally, ensure that your code will degrade gracefully when CSS is disabled in the user’s browser. To test this, either turn styles off in every browser or use a text browser such as Lynx.

15. Ensuring that your code degrades gracefully is obviously important, but many people forget that some visitors will have a dodgy browser or have styles turned off, so check that your fallbacks work.

16. Every browser has a built-in debugger. In IE and Firefox you can get to the inspector by hitting F12; for Chrome, Safari and Opera, press Ctrl + Shift + I.

17. Browser emulators can’t replace the real thing, so use a real or virtualized edition of a browser or device.

18. Did you know that PHP code can create dynamic CSS files? Here’s a tutorial on that. Just give the file a .php extension and ensure that the file declares the document header with a text/css content type.

19. Naming CSS files can be tricky. One of the best ways to approach the task is to keep file names short and descriptive, like screen.css, styles.css or print.css.

20. Any code or process you create is valuable, and recycling what you’ve produced for other projects is not a bad thing: pre-existing code is a great timesaver, and this is how JavaScript and CSS frameworks are born.

21. While comments in CSS files can assist other people who read or maintain them, avoid writing comments unless they are required. Comments consume bandwidth. Write CSS in a self-explanatory manner by organizing them intuitively and using good naming conventions.

22. If you’re struggling to remember what’s available in CSS (or even CSS3), get some cheat sheets. They’re simple and can help you get used to the syntax. Here are some excellent CSS cheat sheets: CSS Cheat Sheet (Added Bytes), CSS Shorthand Cheat Sheet (Michael Leigeber), CSS 2.1 and CSS 3 Help Cheat Sheets (PDF) (Smashing Magazine).

23. Bad code breaks more websites than anything else. Validate your code by using the free, web-based W3C CSS Validation Service to reduce potential faults.

24. Vendor-specific CSS won’t validate under the current W3C specifications (CSS2.1), but could give your design some useful enhancements. Plus, if you’d like to use some CSS3 for progressive enhancement, there’s no way around using them in some instances. For example, the -webkit-transform and -moz-transform property was used to progressively enhance these CSS3-animated cards for users using Safari, Chrome, and Mozilla Firefox.

25. Keep multiple CSS files in a single directory, with an intuitive name such as css/. If your website has hundreds of pages, maintainability and information architecture are vital.

26. Be careful when using the media attribute in your HTML declaration for an external CSS file. You might be unable to use media queries to better provide pre-cached alternative visuals.

27. If you find elements that use the same properties and values, group them together by using a comma (,) to separate each selector. This will save you from repetition.

For example, if you have the following:

h1 { color:#000; }  h2 { color:#000; }

Combine them as such:

h1, h2 { color:#000; }

28. Printer-friendly stylesheets are very important if you want to save your visitors’ ink and paper. Use the @media print at-rule, and remove anything that isn’t necessary on the printed page.

29. Accessibility also has to do with how the written word is spoken. The aural (now deprecated in CSS) and speech media queries can improve usability for screen readers.

30. Unfortunately, the handheld media query in CSS isn’t widely supported. If you want your website to work on mobile devices, don’t depend on it to serve the correct visuals to mobile devices.

31. Take the time to eliminate duplicate references and conflicts in your CSS. It will take some time, but you’ll get a more streamlined render and fewer bytes in your files.

32. When working with mouse hover events, deal with the (1) :link pseudo-class, then (2) :visited, then (3) :hover and finally (4) :active — in that order. This is necessary because of the cascade.

33. Making a website work well on Apple iOS devices is straightforward: to scale your design, just use CSS3 media queries with the appropriate min-width and max-width values. Here’s a tutorial for that.

34. Make the most of CSS inheritance by applying required styles to parent elements before applying them to the children. You could hit several birds with one stone.

35. You can apply multiple classes to an element with space separation, which is great if you want to share properties with numerous elements without overwriting other styles.

36. If you don’t want to deal with IE6′s conditional comment quirks–they require a separate CSS file–then you can use the star hack (* html) selector, which is clean and validates.

37. HTML tooltips are fine for plain text, but the :hover pseudo-class for CSS tooltips gives you more options for showing styled content. Check out this tutorial on how to create CSS-only tooltips.

38. Using attribute selectors, you can add icons or unique styles depending on the file type you link to in an anchor. Here’s an example with which you can add style to a PDF link: a[href$='.pdf].

39. You can also use attribute selectors to target a specific pseudo-protocol such as mailto or skype: [href^="skype:"].

40. Rendering CSS takes time, and listing selectors adds bytes. Reduce the workload of a renderer by using only the selectors you require (an id is better than many child references).

41. Not everyone will agree with this, but I recommend writing every “custom” selector down as a class (before making it an id) to help eliminate duplicate entries.

42. When structuring your CSS file by selectors, the convention is to list elements, then classes (for common components) and finally any ids (for specific, unique styles).

43. Naming conventions for selectors are important. Never use names that describe physical attributes (such as redLink), because changing the value later could render the name inappropriate.

44. Case sensitivity relates to naming conventions. Some people use dashes (e.g. content-wrapper) or underscores (i.e. content_wrapper), but I highly recommend using camel case (e.g. contentWrapper) for simplicity.

45. The universal selector (*) is used widely in CSS reset mechanisms to apply specific properties to everything. Avoid it if you can; it increases the rendering load.

46. With CSS3 media queries, you can easily target the orientation of a viewport with portrait or landscape mode. This way, handheld devices make the most of their display area.

47. Apple’s devices are unique in that they support a <meta name=”viewport”> tag, which has stylistic value attached to it. You can use this to force the screen to zoom at a fixed rate of 100%.

48. The two CSS3 pseudo-elements, :target and :checked have great potential. They apply their designated style only to certain events and can be useful as hover event alternatives.

49. Embedding content in CSS is a unique way to give anchor links some description in printer-friendly stylesheets. Try them with the ::before or ::after pseudo-elements.

50. IDs can serve a dual purpose in CSS. They can be used to apply styling to a single element and to act as an anchoring fragment identifier to a particular point on the page.

51. Many designs are focused on grids and the rectangular regions of the viewport. Instead, create the illusion of breaking out of the box for added effect.

52. If margin: auto; on the left and right sides isn’t getting you the central point you desire, try using left: 50%; position: absolute; and a negative margin half the width of the item.

53. Remember that the width of an item constitutes the specified width as well as the border width and any padding and margins. It’s basically a counting game!

54. Another controversial tip here: don’t use CSS resets. They are generally not needed if you take the time to code well.

55. A CSS framework such as Blueprint or YUI Grids CSS might assist you speed up development time. It’s a bit of extra code for the user to download, but it can save you time.

56. Remember that Internet Explorer 6 does not support fixed positioning. If you want a menu (or something else) to be sticky, it’ll require some hacks or hasLayout trickery.

57. Whitespace in web designs is amazing; don’t forget it. Use margins and padding to give your layout and its content some breathing room. You’ll create a better user experience.

58. If one thing overcomplicates the task of scaling a design the way you want, it’s using inconsistent measurements. Standardize the way you style.

59. Different browsers have different implementations; visually impaired users may want to zoom in, for example. Give your layout a quick zoom-test in web browsers to ensure the style doesn’t break!

60. Most browsers can use box-shadow without extra HTML. IE can do the same with filter: progid:DXImageTransform.Microsoft.Shadow(color=’#CCCCCC’, Direction=135, Strength=5);

61. Rounded corners aren’t as difficult to make as they used to be. CSS3 lets you use the border-radius property to declare the curvature of each corner without surplus mark-up and the use of images.

62. One disadvantage of liquid layouts is that viewing on a large screen makes content spill across the viewport. Retain your desired layout and its limits by using min-width and max-width.

63. WebKit animations and transitions might work only in Safari and Chrome, but they do add a few extra unique, graceful flourishes worthy of inclusion in interactive content.

64. If you want to layer certain elements over one another, use the z-index property; the index you assign will pull an element to the front or push it behind an item with a higher value.

65. Viewport sizes aren’t a matter of resolution. Your visitors may have any number of toolbars, sidebars or window sizes (e.g. they don’t use their browsers maximized) that alter the amount of available space.

66. Removing clutter from an interface using display:none might seem like a good idea, but screen-reader users won’t be able to read the content at all.

67. Be careful with the overflow CSS property when catering to touch-screen mobile devices. The iPhone, for example, requires two fingers (not one) to scroll an overflowed region, which can be tricky.

68. Have you ever come across CSS expressions? They were Microsoft’s proprietary method of inserting DOM scripts into CSS. Don’t bother with them now; they’re totally deprecated.

69. While the CSS cursor property can be useful in certain circumstances, don’t manipulate it in such a way as to make finding the cursor on the screen more difficult.

70. Horizontal scrolling might seem like a unique way to position and style content, but most people aren’t used to it. Decide carefully when such conventions should be used.

71. Until Internet Explorer 9 is final, CSS3 will have some critical compatibility issues. Don’t rely too heavily on it for stable layouts. Use progressive enhancement concepts.

72. CSS makes it possible to provide information on demand. If you can give people information in small chunks, they’ll be more likely to read it.

73. When showcasing a menu in CSS, be consistent in implementation. People want to know about the relationship between objects, and it’s important to avoid dissonance.

74. CSS isn’t a solution to all of your layout woes–it’s a tool to aid your visual journey. Whatever you produce should be usable and logically designed for users (not search engines).

75. Once your layout is marked up with CSS, get feedback on how usable it really is; ask friends, family, co-workers, visitors or strangers for their opinions.

76. Squeezing content too close together can decrease overall readability. Use the line-height property to space lines of text appropriately.

77. Be cautious about letter-spacing: too much space and words will become illegible, too little and the letters will overlap.

78. Unless you have good reason, don’t uppercase (i.e. text-transform:uppercase; ) long passages of text (e.g. HEY GUYS AND GALS WHAT’S UP?). People hate reading what comes off as shouting.

79. Accessible websites have good contrasting colors. Tools exist to measure foreground colors against background colors and give you a contrast ratio. Check out this list of tools for checking your design’s colors. Be sure your text is legible.

80. Remember that default styles might differ greatly from browser to browser. If you want stylistic flourish, reinforce the behavior in the stylesheet.

81. In the old days, the number of colors that a screen could display was rather limited. Some people still use old monitors, but the need for web-safe colors has drastically reduced.

82. Building a font stack is essential when making a design degrade gracefully. Make sure that fallback typefaces exist in case the one you request isn’t available.

83. With Vista, Windows 7 and MS Office 07–10 (and their free viewers), a number of cool new web-safe fonts have become available, such as Candara, Calibri and Constantina. Read about Windows fonts.

84. Plenty of smartphone apps can boost your ability to build a stylesheet, but Typefaces for the iPhone and other iOS4 devices is particularly useful because it shows you every font installed.

85. Web-safe fonts are no guarantee; people could quite possibly uninstall a font even as ubiquitous as Arial (or Comic Sans!). Then their browsers wouldn’t be able to render it.

86. Avoid underlining content with the text-decoration property unless it’s a real link. People associate underlined text with hyperlinks, and an underlined word could give the impression that a link is broken.

87. Avoid the temptation to use symbolic typefaces like Wingdings or Webdings in the layout. It might save KBs on imagery, but it’ll serve nonsensical letters to screen-reader users.

88. Remember that @font-face has different file format requirements depending on which browser the user is on, such as EOT, WOFF, TTF and OTF (as you would find on a PC). Serve the appropriate format to each browser.

89. The outline property is seriously underused as an aid to web accessibility. Rather than leaving it set to the default value, use border styles to enhance an active event’s visibility.

90. Smartphones do not have the same level of core support for web typography that desktop browsers do, which means fewer web-safe fonts and no conventional @font-face embedding.

91. Cross-browser opacity that degrades gracefully can be applied using the -ms-, -moz-, -khtml- vendor prefixes and the filter: alpha(opacity=75); property for Internet Explorer.

92. You can make background-image bullets by using list-style-type:none;, adding a padding-left indent and positioning the background-image to the left (with the required pixel offset).

93. Helping users identify an input box is easy; just add a background image of the name (like “Search” or “Password”) and set it so that the image disappears when the box is clicked on by using the :focus pseudo-class and then setting the background property to none.

94. Large and visible click regions enhance the usefulness and usability of anchor links, which in turn guide people among pages. Be attentive when you style these.

95. Remember that background images do not replace textual content. If a negative indent is applied, for example, and images are disabled, then the title will be invisible.

96. Navigation items need to be labeled appropriately. If you use a call-to-action button or an image-based toolbar, make sure a textual description is available for screen readers.

97. If the idea of applying opacity with a bunch of proprietary elements doesn’t appeal to you, try RGBA transparency (in CSS3) instead of background-color: rgba(0,0,0,0.5);.

98. If your visitors use IE6, avoid using px as the unit of measurement for text. IE6 users have no zoom functionality; they rely on text resizing, which doesn’t work with px. Use a relative unit instead, such as em.

99. Providing alternative stylesheets for supported browsers such as Firefox and Opera can enhance readability, as in the case of high-contrast alternatives.

100. If you find choosing colors difficult, web-based tools like Adobe Kuler, desktop tools like ColorSchemer Studio and mobile apps like Palettes Pro might help.

Source: http://sixrevisions.com/


I have a site with full body bg as repeat-x but content part in center position with 900px width, and I done it as my label best.  But the problem is when I load it as “Restore Down” browser window then body bg load as just window size and right side does not get any bg. Below in picture:

Full layout html

Full layout html

Layout as browser "Restore Down" mood view

Layout as browser “Restore Down” mood view

Layout problem as browser "Restore Down" mood view

Layout problem as browser “Restore Down” mood view


I am very much wondering to solve the problem when it’s load with browser Restore Down size. I just add two css properties and able to solve the problem. And it load well as my expectation .

css is

Full layout html

Full layout html

Layout as browser "Restore Down" mood view

Layout as browser “Restore Down” mood view

Layout problem solved as browser "Restore Down" mood view

Layout problem solved as browser “Restore Down” mood view

Forget table, try div

One of the greatest advantage of CSS is the use of “div” to achieve total flexibility in terms of styling. “div” are unlike “table”, where contents are ‘locked’ within a “td”’s cell. It’s safe to say most “table” layouts are achievable with the use of “div” and proper styling, well maybe except massive tabular contents.

What is a Table?

If you are a web designer, the chances of implementing tables in your layout may be plenty. Tables are useful for superior adjustment of data and aligning text and graphics. General syntax of a table starts with “table” and ends with “table” element. Tables are modified using various attributes such as ALIGN, BORDER, CELLPADDING, CELLSPACING, WIDTH etc… The tags “tr” and “td” are useful in defining each cell of a table.

It would be easier to understand, if we imagine a table as an excel sheet. The entire spreadsheet would be in horizontal and vertical rows. Rows start with numbers and columns start with alphabets. A combination of each row and a column would form a cell (A1). In order to incorporate a similar feel on web pages with advance attributes, we use tables.

This website clearly explains the various parameters used in tables with examples.
Let us consider a simple example to understand a table structure.

<table border=”1″ height="100%" width="100%" align="left" cellpadding="0" cellspacing="0">
		<th>Another Heading</th> </tr>
		<td>row 1, cell 1</td>
		<td>row 1, cell 2</td> </tr>
		<td>row 2, cell 1</td>
		<td>row 2, cell 2</td> 

What is a DIV?

Division tags are block-level elements which appear as rectangular blocks with specific height and width on a web page. They are used to divide the content of webpage and apply independent formatting. They can be used to enclose paragraphs, headers and other block elements.

“div” tags when used with style sheets is commonly referred as Cascading Style Sheets. They allow website to be independent of data. Document layout, height and width of columns or rows, adding colors; adjusting the font family, font size, adding images, using additional attributes to align the web elements can all be done by editing a single style sheet.

We added some useful information on CSS on the later part of this article.

We can style each “div” tag differently to suit the layout. For example:

<div id="container">
	<div id="header">Header part will go from here...</div>
	<div id="wrapper">
		<div id="leftpane">Left part will go from here...</div>
		<div id="content">Content part will go from here...</div>
		<div id="rightpane">Right part will go from here...</div>
	<div id="footer">Footer part will go from here...</div>

All css Selectors

Universal Selector

This selector matches any element name in the document’s language. If a rule does not have an explicit selector, then the universal selector is inferred.


* {color: red;}
div * p {color: blue;}

Type/Tag Selector

This selector matches the name of an element in the document’s language. Every instance of the element name is matched. (CSS1 referred to these as element selectors.)


body {background: #FFF;}
p {font-size: 1em;}

ID Selector

In languages that permit it, such as HTML, an ID selector using “hash notation” can be used to select elements that have an ID containing a specific value or values. The name of the ID value must immediately follow the octothorpe (#). If no element name precedes the octothorpe, the selector matches all elements containing that ID value.


h1#page-title {font-size: 250%;}
body#home {background: silver;}
#example {background: lime;}

Class Selector

In languages that permit it, such as HTML, SVG, and MathML, a class selector using “dot notation” can be used to select elements that have a class containing a specific value or values. The name of the class value must immediately follow the dot. Multiple class values can be “chained” together. If no element name precedes the dot, the selector matches all elements containing that class value.


p.urgent {color: red;}
a.external {font-style: italic;}
.example {background: olive;}

Descendant Selector

This allows the author to select an element based on its status as a descendant of another element. The matched element can be a child, grandchild, great-grandchild, etc., of the ancestor element. (CSS1 referred to these as contextual selectors.)


body h1 {font-size: 200%;}
table tr td div ul li {color: purple;}

Child Selector

This type of selector is used to match an element based on its status as a child of another element. This is more restrictive than a descendant element, since only a child will be matched.


div > p {color: cyan;}
ul > li {font-weight: bold;}

Adjacent Sibling Selector

This allows the author to select an element that is the following adjacent sibling of another element. Any text between the two elements is ignored; only elements and their positions in the document tree are considered.


table + p {margin-top: 2.5em;}
h1 + * {margin-top: 0;}

Simple Attribute Selector

This allows authors to select any element based on the presence of an attribute, regardless of the attribute’s value.


a[rel] {border-bottom: 3px double gray;}
p[class] {border: 1px dotted silver;}

Exact Attribute Value Selector

This allows authors to select any element based on the precise complete value of an attribute.


a[rel="Home"] {font-weight: bold;}
p[class="urgent"] {color: red;}

Partial Attribute Value Selector

This allows authors to select any element based on a portion of the space-separated value of an attribute. Note that [class~="value"] is equivalent to .value (see above).


a[rel~="friend"] {text-transform: uppercase;}
p[class~="warning"] {background: yellow;}

Beginning Substring Attribute Value Selector

This allows authors to select any element based on a substring at the very beginning of an attribute’s value.


a[href^="/blog"] {text-transform: uppercase;}
p[class^="test-"] {background: yellow;}

Ending Substring Attribute Value Selector

This allows authors to select any element based on a substring at the very end of an attribute’s value.


a[href$=".pdf"] {font-style: italic;}

Arbitrary Substring Attribute Value Selector

This allows authors to select any element based on a substring found anywhere within an attribute’s value.


a[href*="oreilly.com"] {font-weight: bold;}
div [class*="port"] {border: 1px solid red;}

Language Attribute Selector

This allows authors to select any element with a lang attribute whose value is a hyphen-separated list of values, starting with the value provided in the selector.


html[lang|="en"] {color: gray;}

Pseudo-Classes and Pseudo-Elements


This applies to an element during the period in which it is activated. The most common example of this is clicking on a hyperlink in an HTML document: during the time that the mouse button is held down, the link is active. There are other ways to activate elements, and other elements can in theory be activated, although CSS doesn’t define this.


a:active {color: red;}
*:active {background: blue;}


This allows the author to insert generated content at the end of an element’s content. By default, the pseudo-element is inline, but this can be changed using the property display.


a.external:after {content: " " url(/icons/globe.gif);}
p:after {content: " | ";}


This allows the author to insert generated content at the beginning of an element’s content. By default, the pseudo-element is inline, but this can be changed using the property display.


a[href]:before {content: "[LINK] ";}
p:before {content: attr(class);}


With this pseudo-class, an element is matched only when it is the first child of another element. For example, p:first-child will select any p element that is the first child of some other element. It does not, as is commonly assumed, select whatever element is the first child of a paragraph; for that, an author would write p > *:first-child.


body *:first-child {font-weight: bold;}
p:first-child {font-size: 125%;}


This is used to style the first letter of an element. Any leading punctuation should be styled along with the first letter. Some languages have letter combinations that should be treated as a single character, and a user agent may apply the first-letter style to both. Prior to CSS2.1, :first-letter could be attached only to block-level elements. CSS2.1 expands its scope to include all elements. There is a limited set of properties that can apply to a first letter.


h1:first-letter {font-size: 166%;}
a:first-letter {text-decoration: underline;}


This is used to style the first line of text in an element, no matter how many or how few words may appear in that line. :first-line can be attached only to block-level elements. There is a limited set of properties that can apply to a first line.


p.lead:first-line {font-weight: bold;}


This applies to an element during the period in which it has focus. One example from HTML is an input box that has the text-input cursor within it; that is, when the user starts typing, text will be entered into that box. Other elements, such as hyperlinks, can also have focus, although CSS does not define which ones.


a:focus {outline: 1px dotted red;}
input:focus {background: yellow;}


This applies to an element during the period in which it is “hovered.” Hovering is defined as the user designating an element without activating it. The most common example of this is moving the mouse pointer inside the boundaries of a hyperlink in an HTML document. Other elements can in theory be hovered, although CSS doesn’t define which ones.


a[href]:hover {text-decoration: underline;}
p:hover {background: yellow;}


This matches elements based on their human language encoding. Such language information must be contained within or otherwise associated with the document; it cannot be assigned from CSS. The handling of :lang is the same as for |= attribute selectors.


html:lang(en) {background: silver;}
*:lang(fr) {quotes: '« ' ' »';}


This applies to a link to a URI that has not been visited; that is, the URI to which the link points does not appear in the user agent’s history. This state is mutually exclusive with the :visited state.


a:link {color: blue;}
*:link {text-decoration: underline;}


This applies to a link to a URI that has been visited; that is, the URI to which the link points appears in the user agent’s history. This state is mutually exclusive with the :link state.


*:visited {color: gray;}

css Absolute

If you position an element (an image, a table, or whatever) absolutely on your page, it will appear at the exact pixel you specify. Say I wanted a graphic to appear 46 pixels from the top of the page and 80 pixels in from the right, I could do it. The CSS code you’ll need to add into the image is

img {position: absolute ; top: 46px; right: 80px; } 

It is possible to have things overlapping with absolute positioning.

To get layers overlapping each other you need to use the z-index command. Add z-index: 1 in with the positioning code and this element will appear above everything without this command. If you want something else to go over this layer too, add z-index: 2 and so on. The higher the index, the closer the div will appear to the front of the page.

Put the layer that holds your page’s content at the top of your code. This is what readers want to see immediately. Your navigation and other presentational components can then load around this, allowing your reader to begin reading as soon as possible and making your navigation available when it is most likely to be used: after the page has been read.

Advantages of Absolute Positioning

* Full control over where elements are positioned on the page – much more control than is possible with tables.
* The order of the divs in the HTML source code doesn’t matter – once something is absolute positioned it is “pulled out of the flow” of the document, so it can be placed pretty much anywhere in that document. This allows you to have your content before your navigation structures, which is good for accessibility and good for search engine optimisation.

Disadvantages of Absolute Positioning

* Elements can end up overlapping if due care is not taken – especially when the user dramatically resizes the page.
* The footer problem. If you have a layout which uses absolute positioning for one of the columns, there is no way of creating a footer that spans the whole of the bottom of the page without risk of it being overlapped by the absolutely positioned column should that column be longer than the non-positioned column. The solution is either to ensure the static column has more content than the absolute positioned one, or to restrict the footer to taking up space at the bottom of the static column rather than spanning the whole page. See also Footer Beneath Sidebar

css Float

What is Floats?

You can’t float every element on a Web page. To get technical, you can only float block-level elements. These are the elements that take up a block of space on the page, like images (<img/>), paragraphs (<p></p>), divisions (<div></div>), and lists (<ul></ul>). Other elements that affect text, but don’t create a box on the page are called inline elements and can’t be floated. These are elements like span (<span></span>), line breaks (<br/>), strong emphasis (<strong></strong>), or italics (<i></i>).

Where Do They Float?

You can float elements to the right or the left. Any element that follows the floated element will flow around the floated element on the other side.

For example, if I float an image to the left, any text or other elements following it will flow around it to the right. See the example. And if I float an image to the right, any text or other elements following it will flow around it to the left. See the example. An image that is placed in a block of text without any float style applied to it will display as the browser is set to display images. This is usually with the first line of following text displayed at the bottom of the image. See the example.

How Far Will They Float?

An element that has been floated will move as far to the left or right of the container element as it can. This results in several different situations depending upon how your code is written. For these examples, I will be floating a small <div> to the left:

* If the floated element does not have a pre-defined width, it will take up as much horizontal space as required and available, regardless of the float. Note: some browsers attempt to place elements beside floated elements when the width isn’t defined – usually giving the non-floated element only a small amount of space. So you should always define a width on floated elements.
* If the container element is the HTML , the floated div will sit on the left margin of the page.
* If the container element is itself contained by something else, the floated div will sit on the left margin of the container.
* You can nest floated elements, and that can result in the float ending up in a surprising place. For example, this float is a left floated div inside a right floated div.
* Floated elements will sit next to each other if there is room in the container. For example, this container has 3 100px wide divs floated in a 400px wide container.

You can even use floats to create a photo gallery layout. You put each thumbnail (it works best when they are all the same size) in a DIV with the caption and the float the divs in the container. No matter how wide the browser window is, the thumbnails will line up uniformly.

Turning Off the Float

Once you know how to get an element to float, it’s important to know how to turn off the float. You turn off the float with the CSS clear property. You can clear left floats, right floats or both:

clear: left;
 clear: right;
 clear: both;

Any element that you set the clear property for will appear below an element that is floated that direction. For example, in this example the first two paragraphs of text are not cleared, but the third is.

Play with the clear value of different elements in your documents to get different layout effects. One of the most interesting floated layouts is a series of images down the right or left column next to paragraphs of text. Even if the text is not long enough to scroll past the image, you can use the clear on all the images to make sure that they appear in the column rather than next to the previous image.

Images floated to the left and to the right.

The HTML (repeat this paragraph):

Duis aute irure dolor sed do eiusmod tempor incididunt in reprehenderit in voluptate. Cupidatat non proident, ut labore et dolore magna aliqua.

The CSS (to float the images to the left):

img.float { float:left;clear:left; margin:5px;}

And to the right:

img.float { float:right;clear:right; margin:5px;}

Using Floats for Layout

Once you understand how the float property works, you can start using it to lay out your Web pages. These are the steps I take to create a floated Web page:

* Design the layout (on paper or in a graphics tool or in my head).
* Determine where the site divisions are going to be.
* Determine the widths of the various containers and the elements within them.
* Float everything. Even the outermost container element is floated to the left so that I know where it will be in relation to the browser view port.

As long as you know the widths (percentages are fine) of your layout sections, you can use the float property to put them where they belong on the page. And the nice thing is, you don’t have to worry as much about the box model being different for IE or Firefox.

Tag Cloud


Get every new post delivered to your Inbox.