CSS

Using max-width on images can make them disappear in IE8

I recently ran into a problem that was really hard to figure out. I was working on a responsive design where I used img {max-width:100%;} to make sure that images would be downsized rather than overflow in narrower viewports.

It worked great everywhere… until I went to check in IE8. The site’s logo was gone! None of the usual IE bug fixes cured the problem, and it took me quite a while to realise that max-width was part of the problem.

Read full post

Posted in , .

Copyright © Roger Johansson



Useful CSS Snippets for Your Coding Arsenal


  

CSS is a beautiful language but it can also be frustrating at times. Certain CSS solutions don’t work on certain browsers (cough Internet Explorer cough) and much of your time can be spent debugging code.

Thankfully there are lots of great CSS snippets available online that fix common problems and design issues. In this article we have listed 30 CSS snippets that we think you will find very useful.

The Code

1. Chris Poteet’s CSS Browser Reset

Resetting your CSS style allows you to stop cross browser differences. Chris Proteet’s reset code doesn’t work in IE6 however this shouldn’t be a concern any more with use of the browser dropping below 1% in the USA.

/*

Reset Default Browser Styles
- Place first in the listing of external style sheets for cascading.
- Be sure to explicitly set margin/padding styles.
- Styles are not reset that have to do with display (block, inline) are not reset.

By: Chris Poteet & various influences

*/

* {
vertical-align: baseline;
font-family: inherit;
font-style: inherit;
font-size: 100%;
border: none;
padding: 0;
margin: 0;
}
body {
padding: 5px;
}
h1, h2, h3, h4, h5, h6, p, pre, blockquote, form, ul, ol, dl {
margin: 20px 0;
}
li, dd, blockquote {
margin-left: 40px;
}
dt {
font-weight: bold;
}
table {
border-collapse: collapse;
border-spacing: 0;
}

2. Eric Meyer’s CSS Reset

Eric Meyer’s CSS code resets is one of the most popular CSS snippets. It even found it’s way into the Blueprint CSS Framework.

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}

3. How to Create Multiple Borders in CSS3

A cool technique using the box-shadow property that allows you to create multiple borders around an object.

box-shadow:
    0 0 0 2px #000,
    0 0 0 3px #999,
    0 0 0 9px #fa0,
    0 0 0 10px #666,
    0 0 0 16px #fd0,
    0 0 0 18px #000;

4. Tucked Corners

This CSS code will give you the cool ‘tucked corners’ effect that is used on the Gravatar home page.

div.tucked-corners {
	    background: #f6f6f6;
	    height: 380px;
	    margin: 50px auto;
	    padding: 10px;
	    position: relative;
	    width: 580px;
	    -webkit-box-shadow: 0 1px 7px hsla(0,0%,0%,.2);
	       -moz-box-shadow: 0 1px 7px hsla(0,0%,0%,.2);
	            box-shadow: 0 1px 7px hsla(0,0%,0%,.2);
	}
	span.tucked-corners {
	    background: #c4453c;
	    display: block;
	    height: 380px;
	    position: relative;
	    width: 580px;
	    -webkit-box-shadow: inset 0 0 10px hsla(0,0%,0%,.25);
	       -moz-box-shadow: inset 0 0 10px hsla(0,0%,0%,.25);
	            box-shadow: inset 0 0 10px hsla(0,0%,0%,.25);
	}

	/* Top Corner Effect */

	.top-corners:after,
	.top-corners:before {
	    background: #e6e6e6;
	    content: '';
	    height: 50px;
	    position: absolute;
	    top: -25px;
	    width: 100px;
	    z-index: 10;
	    -webkit-box-shadow: 0 6px 9px -8px hsla(0,0%,0%,.5);
	       -moz-box-shadow: 0 6px 9px -8px hsla(0,0%,0%,.5);
	            box-shadow: 0 6px 9px -8px hsla(0,0%,0%,.5);
	}
	.top-corners:after {
	    left: -50px;
	    -webkit-transform: rotate(-45deg);
	       -moz-transform: rotate(-45deg);
	        -ms-transform: rotate(-45deg);
	         -o-transform: rotate(-45deg);
	            transform: rotate(-45deg);
	}
	.top-corners:before {
	    right: -50px;
	    -webkit-transform: rotate(45deg);
	       -moz-transform: rotate(45deg);
	        -ms-transform: rotate(45deg);
	         -o-transform: rotate(45deg);
	            transform: rotate(45deg);
	}

	/* Bottom Corner Effect */

	.bottom-corners:after,
	.bottom-corners:before {
	    background: #e6e6e6;
	    content: '';
	    height: 50px;
	    position: absolute;
	    bottom: -25px;
	    width: 100px;
	    -webkit-box-shadow: 0 6px 9px -8px hsla(0,0%,0%,.5);
	       -moz-box-shadow: 0 6px 9px -8px hsla(0,0%,0%,.5);
	            box-shadow: 0 6px 9px -8px hsla(0,0%,0%,.5);
	}
	.bottom-corners:after {
	    left: -50px;
	    -webkit-transform: rotate(-135deg);
	       -moz-transform: rotate(-135deg);
	        -ms-transform: rotate(-135deg);
	         -o-transform: rotate(-135deg);
	            transform: rotate(-135deg);
	}
	.bottom-corners:before {
	    right: -50px;
	    -webkit-transform: rotate(135deg);
	       -moz-transform: rotate(135deg);
	        -ms-transform: rotate(135deg);
	         -o-transform: rotate(135deg);
	            transform: rotate(135deg);
	}

5. iPad-Specific CSS

Change the general layout of ipad screens and portrait and landscape modes.

@media only screen and (device-width: 768px) {
  /* For general iPad layouts */
}

@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
  /* For portrait layouts only */
}

@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
  /* For landscape layouts only */
}

6. Style links depending on file format

A short CSS snippet that changes the styling of external links, email links and links to pdf documents.

	/* external links */
a[href^="http://"]{
    padding-right: 20px;
    background: url(external.gif) no-repeat center right;
}

/* emails */

a[href^="mailto:"]{
padding-right: 20px;

background: url(email.png) no-repeat center right;

}

/* pdfs */

a[href$=".pdf"]{
padding-right: 20px;
background: url(pdf.png) no-repeat center right;

7. Drop Caps

A great cross-browser snippet that lets you make the first letter of a paragraph stand out.

.firstcharacter { float: left; color: #903; font-size: 75px; line-height: 60px; padding-top: 4px; padding-right: 8px; padding-left: 3px; font-family: Georgia; }

This can also be achieved using CSS3 however it doesn’t work on IE9.

p:first-child:first-letter { float: left; color: #903; font-size: 75px; line-height: 60px; padding-top: 4px; padding-right: 8px; padding-left: 3px; font-family: Georgia; }

8. CSS Sticky Footer

Create a sticky footer for your page. The solution works on all major browsers including Google Chrome and IE8.

CSS

/*
Sticky Footer Solution
by Steve Hatcher 

http://stever.ca

http://www.cssstickyfooter.com

*/

* {margin:0;padding:0;} 

/* must declare 0 margins on everything, also for main layout components use padding, not
vertical margins (top and bottom) to add spacing, else those margins get added to total height
and your footer gets pushed down a bit more, creating vertical scroll bars in the browser */

html, body {height: 100%;}

#wrap {min-height: 100%;}

#main {overflow:auto;
	padding-bottom: 150px;}  /* must be same height as the footer */

#footer {position: relative;
	margin-top: -150px; /* negative value of footer height */
	height: 150px;
	clear:both;} 

/*Opera Fix*/
body:before {/* thanks to Maleika (Kohoutec)*/
content:"";
height:100%;
float:left;
width:0;
margin-top:-32767px;/* thank you Erik J - negate effect of float*/
}

/* IMPORTANT

You also need to include this conditional style in the  of your HTML file to feed this style to IE 6 and lower and 8 and higher.



*/

HTML


<div id="wrap">

	<div id="main">

	</div>

</div>


<div id="footer">

</div>

9. Image Replacement Technique

A handy way of replacing a text page element with an image. The snippet addresses a problem from another solution in which Firefox users noticed a dotted border that goes to the left of the screen.

a.replacement
{
  background: url(dotted-border.png) no-repeat;
  height: 44px;
  width: 316px;
  display: block;
  text-indent: -9999px;
  overflow: hidden;  /*Add this line to the image replacement method*/
}

10. Set body font-size to 62.5% for Easier em Conversion

If you want to have a more flexible layout, you should use em instead of pixels or points. By setting your font size at 62.5% you can easily set your font using em as the value will be a tenth of pixel value.

body {
  font-size: 62.5%; /* font-size 1em = 10px */
}
p {
  font-size: 1.2em; /* 1.2em = 12px */
}

11. Vertically Align Text

If you set the line-height of your paragraph as the same size as it’s parent division you can easily center the text vertically.

div { width:100px; height:100px; }
div p { line-height:100px; }

12. How to Create 3D Text With CSS3

Using the text-shadow property, this snippet will help you create 3D text using CSS only.

p.threeD
{
	text-shadow:
		-1px 1px 0 #ddd,
		-2px 2px 0 #c8c8c8,
		-3px 3px 0 #ccc,
		-4px 4px 0 #b8b8b8,
		-4px 4px 0 #bbb,
		0px 1px 1px rgba(0,0,0,.4),
		0px 2px 2px rgba(0,0,0,.3),
		-1px 3px 3px rgba(0,0,0,.2),
		-1px 5px 5px rgba(0,0,0,.1),
		-2px 8px 8px rgba(0,0,0,.1),
		-2px 13px 13px rgba(0,0,0,.1)
		;
}

13. Wrapping Long URLs and Text Content with CSS

This snippet will stop long lines of text extending over the content area by making sure the content wraps to fit the content width.

pre {
	white-space: pre;           /* CSS 2.0 */
	white-space: pre-wrap;      /* CSS 2.1 */
	white-space: pre-line;      /* CSS 3.0 */
	white-space: -pre-wrap;     /* Opera 4-6 */
	white-space: -o-pre-wrap;   /* Opera 7 */
	white-space: -moz-pre-wrap; /* Mozilla */
	white-space: -hp-pre-wrap;  /* HP Printers */
	word-wrap: break-word;      /* IE 5+ */
	}

14. Fancy Ampersand

Make your ampersands stand out using this short snippet. Simply change the font-family to suit your preference.

.amp {
font-family: Baskerville, 'Goudy Old Style', Palatino, 'Book Antiqua', serif;
font-style: italic;
font-weight: normal;
}

15. Pull Quotes for Improved Reading

Make your quotes stand out more by floating them to the right or left hand side of your content and wrapping content around it.

.pullquote {
width: 300px;
float: right;
margin: 5px;
font-family: Georgia, "Times New Roman", Times, serif;
font: italic bold #ff0000 ; }

16. Rounded Borders Around Images

With CSS3 you can easily place rounded borders around your images using this snippet.

img {
-webkit-border-radius: 25px;
-moz-border-radius: 25px;
border-radius: 25px;
}

17. Image Preloader

Load a small gif in the background of an image first so that it is showed before the main image loads.

img
{
    background: url(img/preloader.gif) no-repeat 50% 50%;
}

18. CSS3 Opacity

By using the opacity property, which lets you see through an element, you can create a layered textured background.

div.L1 { background:#036; opacity:0.2; height:20px; }
div.L2 { background:#036; opacity:0.4; height:20px; }
div.L3 { background:#036; opacity:0.6; height:20px; }
div.L4 { background:#036; opacity:0.8; height:20px; }
div.L5 { background:#036; opacity:1.0; height:20px; }

19. Highlight links that open in a new window

This snippet allows you to easily distinguish links that open in new browser/tab windows by styling them different from other links.

a[target="_blank"]:before,
a[target="new"]:before {
margin:0 5px 0 0;
padding:1px;
outline:1px solid #333;
color:#333;
background:#ff9;
font:12px "Zapf Dingbats";
content: "\279C";
 }

20. The New Bulletproof @Font-Face Syntax

A cross-browser CSS snippet that lets you define your font faces.

@font-face {
	font-family: 'MyFontFamily';
	src: url('myfont-webfont.eot?#iefix') format('embedded-opentype'),
	     url('myfont-webfont.woff') format('woff'),
	     url('myfont-webfont.ttf')  format('truetype'),
	     url('myfont-webfont.svg#svgFontName') format('svg');
	}

21. Flip an Image

A CSS snippet that lets you flip an image. This is particularly useful if you want to flip icons such as arrows.

img {
        -moz-transform: scaleX(-1);
        -o-transform: scaleX(-1);
        -webkit-transform: scaleX(-1);
        transform: scaleX(-1);
        filter: FlipH;
        -ms-filter: "FlipH";
}

22. Email Link With An Image

A quick way of automatically adding a mail image to all of your email links.

a[href^="mailto:"] {
     background: url(images/email.png) no-repeat right top;
     padding-right:10px;
}

23. Beautiful Blockquotes

A neat way of styling your blockquotes to add a bit more punch to them.

blockquote {
     background:#f9f9f9;
     border-left:10px solid #ccc;
     margin:1.5em 10px;
     padding:.5em 10px;
     quotes:"\201C""\201D""\2018""\2019";
}
blockquote:before {
     color:#ccc;
     content:open-quote;
     font-size:4em;
     line-height:.1em;
     margin-right:.25em;
     vertical-align:-.4em;
}
blockquote p {
     display:inline;
}

24. Browser CSS hacks

A large list of browser hacks to make sure your website looks consistent across all browsers.

/***** Selector Hacks ******/

/* IE6 and below */
* html #uno  { color: red }

/* IE7 */
*:first-child+html #dos { color: red } 

/* IE7, FF, Saf, Opera  */
html>body #tres { color: red }

/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body #cuatro { color: red }

/* Opera 9.27 and below, safari 2 */
html:first-child #cinco { color: red }

/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho {  color: red }

/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
 #diez  { color: red  }
}

/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
 #veintiseis { color: red  }
}

/* Safari 2 - 3.1 */
html[xmlns*=""]:root #trece  { color: red  }

/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=""] #catorce { color: red  }

/* Everything but IE6-8 */
:root *> #quince { color: red  }

/* IE7 */
*+html #dieciocho {  color: red }

/* Firefox only. 1+ */
#veinticuatro,  x:-moz-any-link  { color: red }

/* Firefox 3.0+ */
#veinticinco,  x:-moz-any-link, x:default  { color: red  }

/* FF 3.5+ */
body:not(:-moz-handler-blocked) #cuarenta { color: red; }

/***** Attribute Hacks ******/

/* IE6 */
#once { _color: blue }

/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }

/* Everything but IE6 */
#diecisiete { color/**/: blue }

/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }

/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }

/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */

/* IE8, IE9 */
#anotherone  {color: blue\0/;} /* must go at the END of all rules */

25. How To Change The Default Text Selection Color on your Blog

Change the color of highlighted text by adding this little CSS snippet to your stylesheet.

::selection {
   background: #ffb7b7; /* Safari */
        color: #ffffff;
   }
::-moz-selection {
   background: #ffb7b7; /* Firefox */
        color: #ffffff;
   }

26. Clearfix

Clear floated elements easily by creating a CSS clear class.

.clearfix:after {
	visibility: hidden;
	display: block;
	font-size: 0;
	content: " ";
	clear: both;
	height: 0;
}

.clearfix { display: inline-block; }

/* start commented backslash hack \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* close commented backslash hack */

27. Hide Logo Text With Text Indent

Make your logo is SEO friendly by using this snippet for your h1 tag. The snippet ensures that the logo text is not displayed on the page.

h1 {
        text-indent:-9999px;
        margin:0 auto;
        width:400px;
        height:100px;
        background:transparent url("images/logo.jpg") no-repeat scroll;
}

28. Reset all Text Colors and Background Colors

Reset all text and background colours. The snippet sets everything back to black text on a white background though you can change these colours accordingly.

* {
     color: black !important;
     background-color: white !important;
     background-image: none !important;
}

29. Multiple Background Images

Use multiple background images with this useful CSS3 snippet.

#multiple-images {
   background: url(image_1.png) top left no-repeat,
   url(image_2.png) bottom left no-repeat,
   url(image_3.png) bottom right no-repeat;
}

30. Linear Gradient

This CSS code will allow you to create a linear gradient in the background of an element. This works on all major browsers however some older browsers don’t display it properly (particularly older versions of IE).

background-image: -webkit-linear-gradient(top, #F0ECE8 0%, #D8D3C8 100%);
background-image: -moz-linear-gradient( top, #F0ECE8 0%, #D8D3C8 100%);
background-image: -o-linear-gradient( top, #F0ECE8 0%, #D8D3C8 100%);
background-image: linear-gradient( top, #F0ECE8 0%, #D8D3C8 100%);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #F0ECE8), color-stop(1, #D8D3C8) );
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=’#F0ECE8?, endColorstr=’#D8D3C8?,GradientType=0 );

We hope that you enjoyed the post and found it as useful as we’d hoped. If you know of any other useful CSS snippets that you keep handy that we neglected, please share them with us in the comment area.

(rb)


Resolution Independence With SVG


  

In this article, we’ll look at Scalable Vector Graphics (SVG), one of the most underused technologies in website development today.

Before diving into an example, let’s consider the state of the Web at present and where it is going. Website design has found new vigor in recent years, with the evolving technique of responsive design. And for good reason: essentially, responsive website design moves us away from the fixed-width pages we’ve grown accustomed to, replacing them with shape-shifting layouts and intelligent reflowing of content. Add to that a thoughtful content strategy and mobile-first approach, and we’re starting to offer an experience that adapts across devices and browsers to suit the user’s context.

When we look at the breadth of Web-enabled devices, responsive design is sure to provide a better user experience. Scrolling horizontally, panning and zooming the viewport have their place in user interface design, but forcing the user to do these things just to navigate a website quickly becomes tedious. Fitting the website to the viewport is about more than just layout: it’s also about resolution. In this article, I’ll demonstrate why SVG is a perfect addition to future-friendly Web development.

Introducing SVG

SVG offers a truly resolution-independent technique for presenting graphics on the Web. SVG is a vector graphics format that uses XML to define basic properties such as paths, shapes, fonts and colors, and more advanced features such as gradients, filters, scripting and animation. Create the file once and use it anywhere, at any scale and resolution.

Consider the use cases: UI and navigation icons, vector-style illustrations, patterns and repeating backgrounds. For all of these, a scalable graphic is the perfect solution from a visual standpoint, and yet fixed-resolution images are still the norm. In the example below, we’ll show you how to expand on a common development technique to take advantage of SVG.

Resolution independence with SVG

A Case Study: CSS Sprites

We all know about the CSS sprites technique. (If you don’t, then have a quick read through Sven Lennartz’ article. And Louis Lazaris points out its pros and cons.) In the example below, we’ll show how seamlessly SVG replaces normal raster images. If this technique is not for you, you can certainly imagine a whole array of similar situations in which to use SVG.

Vector icons play a big role in user interface design. Pictures express concepts with vivid clarity, whereas their textual counterparts might carry ambiguity. In UI design, where space is scarce, a simple illustrated icon could be greatly welcome.

I’ve mocked up the following example:

An icon based UI menu

I’ll be first to admit that this row of icons won’t win any design awards, but it will suffice for the sake of this article! Let’s look at the HTML:

<div class="actions">
   <a class="a-share" href="#">Share</a>
   <a class="a-print" href="#">Print</a>
   <a class="a-tag" href="#">Tag</a>
   <a class="a-delete" href="#">Delete</a>
</div>

I’ve kept the HTML to a minimum for clarity, but in practice you’d probably want to mark it up with an unordered list. And you’ll almost certainly want to replace those hashes with real URLs (even if JavaScript provides the functionality, having a fallback is nice). Let’s look at the CSS:

.actions {
   display: block;
   overflow: auto;
}

.actions a {
   background-image: url('sprite.png');
   background-repeat: no-repeat;
   background-color: #ccc;
   border-radius: 5px;
   display: block;
   float: left;
   color: #444;
   font-size: 16px;
   font-weight: bold;
   line-height: 20px;
   text-decoration: none;
   text-shadow: 0 -1px 2px #fff;
   padding: 10px 20px 10px 40px;
   margin-right: 5px;
}

.a-share  { background-position: 10px 0; }
.a-print  { background-position: 10px -40px; }
.a-tag    { background-position: 10px -80px; }
.a-delete { background-position: 10px -120px; }

Note the fixed-pixel sizing and the PNG background, which we can see below framed in full Photoshop production glory:

A PNG sprite in Photoshop

This implementation of a CSS sprite is basic, and at today’s standard, it’s not good enough! How can we enhance this? First, let’s consider the following issues:

  1. We’ve rasterized the image at a very early stage. Even at full size, icons in which points sit between pixels, such as the one for “Print,� have blurred.
  2. If we zoom in, the image will blur or pixellate even more; there is no additional data to re-render the image at larger sizes.
  3. Everything has a fixed size, which is neither good for responsive design nor good for accessibility, because the browser’s default font size is ignored.

As you’ve probably guessed by now, we’ll show you how SVG solves these problems. But first, let’s reiterate each point thoroughly to understand the issues at large.

1. Rasterization

Devices such as modern smartphones have a very high pixel density; some already surpass the 300 pixels-per-inch (PPI) mark that is assumed to be the limit of the human eye’s ability to distinguish fine details. A pixel has no real-world equivalent in size until it sits on a screen of fixed dimension (say, 3.5 inches diagonally) and fixed resolution (say, 640 × 960 pixels). At this scale, text with a font size of 16 pixels would be incredibly small to the eye. For this reason, devices simply cannot translate 1 CSS pixel unit to 1 device pixel; instead, they double up. Thus, a 16-pixel font size actually takes over 32 pixels when rendered.

The same applies to images; but they are already rasterized, so doubling up the pixels has no benefit. In our example, each icon has been rasterized at around 25 × 25 pixels (the whole sprite being 30 × 160), so they cannot take advantage of the double pixel ratio. One solution is to use CSS media queries to detect the pixel ratio. This is already implemented in Webkit- and Gecko-based browsers.

To improve our example, we can add the following CSS declaration:

@media only screen and (-webkit-min-device-pixel-ratio: 2)  {
   .actions a {
      background-image: url('sprite@2x.png');
      background-size: 30px 160px;
   }
}

The alternate background image supplied in the code above has been saved at 60 × 320 pixels (i.e. double the original dimensions). The background-size property tells CSS to treat it smaller. Significantly, now the device has the additional data to render a better image (if capable).

This solution isn’t bad, but it doesn’t solve the problems we’ll run into in points 2 and 3 below. It also requires that we maintain multiple files of increasing size: a potential burden on bandwidth and a real hassle. For non-vector images, such as photography in JPG format, we can’t do much more than that.

2. Zooming

At their default size, our rasterized icons look acceptable, at least on low-pixel-density screens. However, should the user zoom in on the Web page, these little UI delights will degrade very quickly.

A PNG sprite zoomed in and blurred.

Zooming is a common action when users find a website too small for comfortable viewing. Or, to put it another way, websites that are designed too small are very common. There is really no “perfect� size, because almost everyone has at least some level of visual impairment, since our eyes inevitably deteriorate with age. Secondly, with the rapid increase in touchscreen devices, pinch-to-zoom has become the standard way to enlarge fixed-sized content designed for larger screens (i.e. much of the Web today).

We should develop websites in a way that minimizes the need for user input — that’s where responsive design comes in (see point 3 below) — but zooming is here to stay. There’s simply no way to provide pre-rasterized images for every level of zoom (in theory, an infinite scale). Scalable graphics are the solution, and we’ll show you how to enhance our example. But first, a related word on fixed sizing.

3. Fixed Sizes

Presenting page elements at fixed sizes forces many users to zoom, but it also disables a very useful browser feature. Users can set their preferred font size (the default in browsers is 16 pixels). By sizing everything in pixels, we override this preference. Sizing elements based on this default is much better, so that, if the text is bigger, everything adjusts to match. This essentially mimics the zooming effect but happens without the user having to manually do it on every visit. Ethan Marcotte has written a great article that explains relative font sizes.

Let’s re-implement our sprite example with a solution to these three issues.

A Scalable Implementation

Here is the HTML again. We don’t need to change anything here.

<div class="actions">
   <a class="a-share" href="#">Share</a>
   <a class="a-print" href="#">Print</a>
   <a class="a-tag" href="#">Tag</a>
   <a class="a-delete" href="#">Delete</a>
</div>

The updated CSS is where the magic happens:

body { font-size: 100%; }

.actions {
   display: block;
   overflow: auto;
}

.actions a {
   font-size: 1em;
   line-height: 1.25em;
   padding: 0.625em 1.25em 0.625em 2.5em;
   margin-right: 0.3125em;
   border-radius: 0.3125em;
   background-image: url('sprite.svg');
   -webkit-background-size: 1.875em 10em;
   -o-background-size: 1.875em 10em;
   -moz-background-size: 1.875em 10em;
   background-size: 1.875em 10em;
   /* styles carried over from the original implementation */
   background-repeat: no-repeat;
   background-color: #ccc;
   color: #444;
   display: block;
   float: left;
   text-decoration: none;
   text-shadow: 0 -1px 2px #fff;
}

.actions-em .a-share { background-position: 0.625em 0; }
.actions-em .a-print { background-position: 0.625em -2.5em;  }
.actions-em .a-tag { background-position: 0.625em -5.0em;  }
.actions-em .a-delete { background-position: 0.625em -7.5em;  }

In this version, we’ve made the following changes:

  • The background-image is now an SVG file.
  • All sizes are based on the default of 16 pixels, or 1 em. If the user’s default is larger or smaller, then everything will scale relatively. (If you multiple each em size by 16, you’ll get the number of pixels used in our initial fixed-size example.)
  • The background-size is very important. By setting this in em units, we’re telling the browser to scale the sprite relative to everything else. You’ll notice that 1.875 × 10 em multiplied by 16 becomes 30 × 160 — the base size at which we produced the sprite in pixels.
  • The background-position of each sprited icon is also based on relative units.

Now that we’re using SVG and relative sizes, we have solved the three big issues highlighted above. A scalable graphic can be rasterized on demand to perfectly suit any device resolution and any zoom level. By using relative sizes, we can continue implementing a responsive design, minimizing as much as possible the need for the user to zoom. We’re also respecting the browser’s default font size, and enabling our design to adapt accordingly.

I actually produced the SVG sprite first and the PNG version from that. (I imported the SVG in Photoshop before exporting it as a PNG — Illustrator’s PNG export had very poor rasterization.) Below is the header in my SVG file. Notice the same 30 × 160 initial size.

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   width="30px" height="160px" viewBox="0 0 30 160" enable-background="new 0 0 30 160" xml:space="preserve">

You can see that the attributes for width and height are set in pixels (width="30px" height="160px") in the opening svg tag (as generated by Adobe Illustrator). This actually causes it to render early in Firefox, before the graphic has scaled to match the em sizes in background-size. Webkit-based browsers seem to scale the SVG perfectly, regardless. I’ve found that editing the SVG file to use em units in these two attributes fixes any rendering issues in Firefox.

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   width="30em" height="160em" viewBox="0 0 30 160" enable-background="new 0 0 30 160" xml:space="preserve">

I don’t know which browser actually implements this scaling correctly, but let it be noted that extra care is needed to ensure cross-browser perfection. Mozilla MDN has an excellent in-depth article, “Scaling of SVG Backgrounds,� which explores more practical examples. For more ideas, see Alex Walker’s article “A Farewell to CSS3 Gradients.�

Here’s a super-close screenshot showing the SVG sprite:

A close-up of a SVG sprite.

The sprite scales beautifully. (Sadly, the same can’t be said for my tacky text-shadow effect.)

It’s best to experience the joys of scalable graphics and relative sizing firsthand. I’ve uploaded a side-by-side live demo demonstrating a combination of all the techniques mentioned above.

Browser Support

At the start of this article, I said that SVG was underused. I believe that has generally been the case due to poor browser support. But things are different now! Browser support for SVG has blossomed over the last year to the point where implementing it is a viable use of development time.

According to the website When Can I Use?, support for SVG across multiple implementations is as follows (I’ve combined support for both CSS’ background-image and HTML’s img source — the most useful attributes):

  • Internet Explorer 9+
  • Firefox 4+
  • Chrome 4+
  • Safari 4+
  • Opera 9.5+

Mobile browser support is also pretty much across the board. If a workable fallback exists for older browsers, then SVG is a very viable solution.

For some of the new additions to Web standards, we can implement them safe in the knowledge that old browsers will simply ignore them and that they aren’t even required. We call this “progressive enhancement�: better browsers get a progressively better experience. SVG is slightly different, because for most practical purposes, it simply replaces other images in CSS backgrounds and HTML elements. The image format — be it SVG, PNG, JPG or GIF — is either supported or it isn’t. We can’t simply follow the practice of progressive enhancement here, because an image failing to render is not an acceptable experience.

Browser Sniffing or Feature Detection?

We could make an educated guess and say that we need to worry only about users of Internet Explorer 6 to 8. In this case, the conditional comments technique for IE-only styles enable us to re-apply a second CSS background-image of a supported format such as PNG, instead of the default SVG background.

Browsing sniffing is always a dangerous game. While Internet Explorer tends to be the main offender, we can never assume it is the only one.

The safer and highly recommended option is to detect SVG support and use it only if it’s found. I suggest using Modernizr if you need to detect multiple features. Modernizr applies a class of svg to your root html element if detected (to which you can apply SVG as a background-image). If you’re using SVG as the source of an image element in HTML, then implementation is a little harder. You’ll have to write more JavaScript to find and replace all sources once support has been established.

The problem with these methods is that the browser will download the fallback image before SVG is detected — the only exception being the conditional comments technique for IE. Users will also likely see a flash of re-styled content when the source image changes. This shouldn’t be the case for long; but at least for now, these problems may be enough to hold you off on SVG usage.

File Size

In our sprite example, the raw SVG file was 2445 bytes. The PNG version was only 1064 bytes, and the double-sized PNG for double-pixel ratio devices was 1932 bytes. On first appearance, the vector file loses on all accounts, but for larger images, the raster version more quickly escalates in size.

SVG files are also human-readable due to being in XML format. They generally comprise a very limited range of characters, which means they can be heavily Gzip-compressed when sent over HTTP. This means that the actual download size is many times smaller than the raw file — easily beyond 30%, probably a lot more. Raster image formats such as PNG and JPG are already compressed to their fullest extent.

Performance

Rendering performance is a concern with SVG, especially on mobile devices, whose hardware is limited. Raster images can be rendered pixel for pixel after decompression and de-encoding. Vector graphics need to be rasterized at a specific resolution every time they’re viewed.

SVG has consistently proved slower than Canvas as a platform for animating vector graphics; but our concern here is basic rendering, not manipulation a thousand times per second, and if that is possible, then simple rendering shouldn’t be a concern. The more intensive SVG features are things like clipping masks and filter effects. These are unnecessary for many practical purposes (like our sprite example), but, if required, the best way to check performance is by testing. A lot of Web development is supported in theory, but in practice results are far from perfect.

Alternative Methods

Hopefully you agree that SVG is extremely useful but not always the ideal solution to resolution independence. Ultimately, the trick is to avoid raster images while maintaining the scalability of visual styles. Below are a few more ideas to think about.

CSS3

You’ve probably already started combining CSS3 properties such as linear-gradient, text-shadow and box-shadow to create more complex styles. Web developer Lea Verou curates a CSS3 pattern gallery that shows off the impressive potential of gradients alone.

CSS3 gradient patterns

In his article “Mobile Web in High Resolution,� Brad Birdsall introduces a technique to maintain pixel perfection for high-resolution displays using the pixel-ratio property.

Then there are pure CSS “icons,� which Faruk Ateş rightly points out as being absolute “madness� — certainly so if you’re using CSS to create a logo! But you could argue the benefits of a small handful of very specific techniques, such as CSS triangles, as demoed by Chris Coyier.

Web Fonts

Dingbat Web fonts and look-a-like Unicode glyphs are two interesting alternatives for vector icons, both with accessibility and semantic challenges. Jon Hicks has a write-up of perhaps the best practice for this. SVG seems a more appropriate technique for icons, but both have an immediate visual impact at high resolutions — and we’ll be paying increasing attention to that in coming years.

Looking Forward

As you can see, SVG usage is very much a possibility, and browser support and performance will only improve in future. What’s important to note from this article is that we really should be building websites that are as resolution-independent as possible.

Consider the “one Web� philosophy and the vast range of devices we use to access it — there is no single user experience. The more we can do to stay device-agnostic, the better. Responsive website design addresses many of these needs and certainly provides many benefits. Using vector graphics may not be as apparent, but its little improvements really do make a difference.

With today’s level of support, many users can experience the beauty of crisp scalable graphics… or perhaps that’s the wrong way to think about it. Most users won’t say “Wow! Kudos on the vectors.� To our dismay, they probably wouldn’t even consider them (and certainly wouldn’t recognize the effort required to craft them). And that’s a good thing; each time we improve the user’s experience, we don’t necessarily need to make a song and dance about it. Letting things continue to grind away under-appreciated is OK. It’s the lack of such things that gets recognized and sniffed at. Raise the user’s expectations in visual aesthetics, and they’ll start to notice the websites that do look shoddy. If you don’t do it, others will.

(al)


© dbushell for Smashing Magazine, 2012.


An Introduction To Object Oriented CSS (OOCSS)





 



 


Have you ever heard the phrase “Content is King”? Being a Web developer, and therefore having a job that’s often linked to content creation, it’s likely you have. It’s a fairly overused but true statement about what draws visitors to a site.

From a Web developer’s perspective, however, some may argue that speed is king. More and more, I’m starting to favour that stance. In recent years many experienced front-end engineers have offered their suggestions on how we can improve the user experience by means of some performance best practices.

Unfortunately, CSS seems to get somewhat overlooked in this area while many developers (for good reason) focus largely on JavaScript performance and other areas.

In this post, I’ll deal with this often overlooked area by introducing you to the concept of object oriented CSS and how it can help improve both the performance and maintainability of your Web pages.

The Principles Of OOCSS

As with any object-based coding method, the purpose of OOCSS is to encourage code reuse and, ultimately, faster and more efficient stylesheets that are easier to add to and maintain.

OOCSS

As described on the OOCSS GitHub repo’s Wiki page, OOCSS is based on two main principles.

Separation of Structure From Skin

Almost every element on a styled Web page has different visual features (i.e. “skins”) that are repeated in different contexts. Think of a website’s branding — the colors, subtle uses of gradients, or visible borders. On the other hand, other generally invisible features (i.e. “structure”) are likewise repeated.

When these different features are abstracted into class-based modules, they become reusable and can be applied to any element and have the same basic result. Let’s compare some before and after code so you can see what I’m talking about.

Before applying OOCSS principles, you might have CSS that looks like this:

#button {
	width: 200px;
	height: 50px;
	padding: 10px;
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

#box {
	width: 400px;
	overflow: hidden;
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

#widget {
	width: 500px;
	min-height: 200px;
	overflow: auto;
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

The three elements above have styles that are unique to each, and they’re applied with the non-reusable ID selector to define the styles. But they also have a number of styles in common. The common styles might exist for branding purposes or consistency of design.

With a little bit of planning and forethought, we can abstract the common styles so the CSS would end up instead like this:

.button {
	width: 200px;
	height: 50px;
}

.box {
	width: 400px;
	overflow: hidden;
}

.widget {
	width: 500px;
	min-height: 200px;
	overflow: auto;
}

.skin {
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

Now all the elements are using classes, the common styles are combined into a reusable “skin” and nothing is unnecessarily repeated. We just need to apply the “skin” class to all the elements and the result will be the same as what the first example would produce, except with less code and a possiblity for further reuse.

Separation of Containers and Content

The second principle described on the OOCSS GitHub wiki page is the separation of containers from their content. To illustrate why this is important, take the following CSS:

#sidebar h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: .8em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 3px 3px 6px;
}

These styles will apply to any third-level headings that are children of the #sidebar element. But what if we want to apply the exact same styles to third-level headings that appear in the footer, with the exception of a different font size and a modified text shadow?

Then we would need to do something like this:

#sidebar h3, #footer h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 2em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 3px 3px 6px;
}

#footer h3 {
	font-size: 1.5em;
	text-shadow: rgba(0, 0, 0, .3) 2px 2px 4px;
}

Or we might end up with something worse:

#sidebar h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 2em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 3px 3px 6px;
}

/* other styles here.... */

#footer h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 1.5em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 2px 2px 4px;
}

Now we’re unnecessarily duplicating styles, and might not realize it (or simply don’t care). With OOCSS, we’re encouraged to give more forethought to what is common among different elements, then separate those common features into modules, or objects, that can be reused anywhere.

The styles that are declared using the descendant selector in those above examples are not reusable, because they are dependent on a particular container (in this case either the sidebar or the footer).

When we use OOCSS’s class-based module building, we ensure that our styles are not dependent on any containing element. This means they can then be reused anywhere in the document, regardless of structural context.

A Real-World Example

To further illustrate how OOCSS can be used, I’ll use something similar to what I did on my site’s recent redesign. After coding the inner header element on my site, I realized that the basic structural styles for the inside of the header could be reused on other elements on the page.

So here’s something along the lines of what I had when I started styling my header:

.header-inside {
	width: 980px;
	height: 260px;
	padding: 20px;
	margin: 0 auto;
	position: relative;
	overflow: hidden;
}

A few of the styles listed here are unique to the .header-inside element. But the rest can form a module that I can reuse. So I can abstract the structural styles into their own reusable class. Here’s the result:

.globalwidth {
	width: 980px;
	margin: 0 auto;
	position: relative;
	padding-left: 20px;
	padding-right: 20px;
	overflow: hidden;
}

.header-inside {
	padding-top: 20px;
	padding-bottom: 20px;
	height: 260px;
}

The styles belonging to the .globalwidth class cover the following:

  • A fixed width
  • Centering using margin: auto
  • Relative positioning to create a positioning context for child elements
  • Left and right padding of 20px
  • Overflow set to “hidden” for clearfixing

Now we’re free to use these styles on any elements that require these same characteristics by simply adding that class to the desired element — without writing a single extra line of CSS.

For my site, I reused these structural styles on the primary content element and the inner footer element. Depending on the design, these styles could also apply to a horizontal navigation element that might appear between the header and the content, or any other element that has a fixed-width and needs to be centered on the page.

After adding the “globalwidth” styles to these elements, the markup would look something like this:

<header>
	<div class="header-inside globalwidth">
	</div>
</header>

<div class="main globalwidth">
</div>

<header>
	<div class="footer-inside globalwidth">
	</div>
</footer>

Some may feel that this type of styles abstraction clutters the HTML and goes against the principle of separating markup from presentation.

But putting aside any debates about how this might affect the markup, no one can question that this abstraction has now made it easier to track down and modify the common styles that are used to structure these three elements.

The Media Object

One of the pioneers of the OOCSS movement is Nicole Sullivan. She’s created a reusable module called the media object which, as she explains, can save hundreds of lines of code.

OOCSS

The media object is a great example of the power of OOCSS because it can contain a media element of any size with content to its right. Although many of the styles that apply to the content inside of it — and even the size of the media element itself — could change, the media object itself has common base styles that help avoid needless repetition.

The Benefits Of OOCSS

I’ve already alluded to some of the benefits of OOCSS. Here I’ll expand on these.

Faster Websites

The performance benefits of OOCSS should be fairly clear. If you have fewer styles that are repeated in your CSS, then this will lead to smaller file sizes and thus faster downloading of those resources.

It’s true that markup will be more cluttered and thus create larger HTML files. But in many cases the amount of loss in markup performance will be greatly surpassed by the amount of gain in stylesheet performance.

Another concept to keep in mind is something that the OOCSS wiki refers to as performance freebies. This refers to the fact that every time you reuse something in your CSS, you’re essentially creating new styled elements with zero lines of CSS code. For large, high-traffic projects, these “freebies” could be a crucial performance gain.

Maintainable Stylesheets

With OOCSS, instead of a constantly growing stylesheet full of specificity wars, you’ll have an easy to maintain set of modules where the natural cascade plays an important role.

When making additions to an existing site, you won’t be adding new styles to the bottom of your stylesheet without regard for what came before. Instead you’ll be reusing existing styles and extending your styles based on existing rule sets.

With this type of forethought, it’s possible to create entire pages while coding very little CSS. Any existing CSS modules can serve as a basis for all new pages, and any new CSS will be minimal. In some cases you might even be able to create a new fully-styled page without coding a single line of CSS.

These maintainability benefits also extend to the robustness of your stylesheets. Because the styles are modular, pages built on OOCSS will be less likely to break when a new developer starts to use the stylesheet.

Points Worth Noting

OOCSS has created a great deal of discussion in the community, raising some controversies. Here I’ll try to dispel a couple of common misconceptions.

You Can Still Use IDs

If you decide to work exclusively in an OOCSS manner, then your styles will be based largely on CSS classes, and you won’t be styling elements using the ID selector.

Because of this, many have falsely claimed that OOCSS encourages dropping the use of IDs completely. But this is not true.

The rule to avoid IDs is, more specifically, don’t use IDs in selectors. So it’s perfectly acceptable to use OOCSS principles (and thus avoid styling using the ID selector) while using IDs in your HTML for JavaScript hooks and fragment identifiers.

Of course, you may have a situation where you already have an ID applied to an element that you know is unique to the page. So, you can save a few bytes by avoiding adding a class to that element and instead style it using an ID selector. But even in this instance, it’s much safer to rely on a class to ensure you don’t run into specificity problems in the future.

Dealing With Smaller Projects

For smaller sites and apps, you could certainly make the case that OOCSS would be overkill. So don’t take this article as an advocacy for OOCSS in all circumstances — it will vary depending on the project.

Nonetheless, I think it’s a good idea, at the very least, to start thinking in terms of OOCSS in all your projects. Once you get the hang of it, I’m sure you’ll find it much easier to get it working on bigger projects where the benefits would be more noticeable and relevant.

Some Guidelines For Implementation

Getting started working with OOCSS could take time. I’m still working on it, so I don’t claim to have all the answers and experience in this area.

But here are some things you might want to start doing to help you get into an OOCSS mode of thinking:

  • Avoid the descendent selector (i.e. don’t use .sidebar h3)
  • Avoid IDs as styling hooks
  • Avoid attaching classes to elements in your stylesheet (i.e. don’t do div.header or h1.title)
  • Except in some rare cases, avoid using !important
  • Use CSS Lint to check your CSS (and know that it has options and method to its madness)
  • Use CSS grids

There will obviously be times when some of these rules will be broken, but overall, these are good habits to develop and will lead to stylesheets that are smaller and easier to maintain.

Follow Nicole Sullivan’s Work

If you want to continue learning about OOCSS, the most important person in the industry to keep up with is Nicole Sullivan.

In addition to posting articles regularly on OOCSS on her blog, Nicole has done a number of presentations with accompanying slideshows. Below are some that you might want to check out:

Conclusion

Many people fear the OOCSS ideology because it seems to go against many of the so-called “best practices” we’ve learned. But once the long-term benefits of using OOCSS are understood, I’m sure many developers will become converts.

Overall I think OOCSS has a bright future in CSS development, and it’s a concept that all developers should start incorporating into their projects — at least on some level — to help create Web pages that are faster, more efficient, and easier to maintain.

(il)


© Louis Lazaris for Smashing Magazine, 2011.


Visited links can only be differentiated by colour

Showing whether a link on a web page has been visited or not can be very useful. One example that many will be familiar with is how it helps you know which links you have already followed from a Google search results page – links to pages you have already visited are a different colour than the other links.

Changing only the colour can be a bit subtle though, especially for people with colour vision deficiency. Depending on which colours are used to differentiate between visited and unvisited links it can be hard to tell them apart. To make the difference more obvious, there are a number of techniques involving background images, generated content (like the one I describe in Check marking visited links), and other CSS properties. However, if you’ve been using any similar tricks to style visited links, it’s time to forget about those and start relying on colour alone.

Read full post

Posted in , .

Copyright © Roger Johansson



  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress