Author: Saim Khalid

  • CSS3 Text Overflow

    Handling Text Overflow in CSS3

    CSS3 introduced several new property properties for modifing the text contents, however some of these properties are existed from a long time. These properties give you precise control over the rendering of text on the web browser.

    Hiding Overflow Text

    Text can overflow, when it is prevented from wrapping, for example, if the value of white-space property is set to nowrap for the containing element or a single word is too long to fit like a long email address. In such situation you can use the CSS3 text-overflow property to determine how the overflowed text content will be displayed.

    You can either display or clip the overflowed text or clip and display an ellipsis or a custom string in palace of the clipped text to indicate the user.

    Values Accepted by the word-break property are: clip and ellipsis and string.

    Example

    p {
    
    width: 400px;
    overflow: hidden;
    white-space: nowrap;
    background: #cdcdcd;
    } p.clipped {
    text-overflow: clip; /* clipped the overflowed text */
    } p.ellipses {
    text-overflow: ellipsis; /* display '…' to represent clipped text */
    }

    Warning: The string value for the text-overflow property is not supported in most of the web browsers, you should better avoid this.


    Breaking Overflow Text

    You can also break a long word and force it to wrap onto a new line that overflows the boundaries of containing element using the CSS3 word-wrap property.

    Values Accepted by the word-wrap property are: normal and break-word.

    Example

    p {
    
    width: 200px;
    background: #ffc4ff;
    word-wrap: break-word;
    }

    Tip: Please check out the individual property reference for all the possible values and the Browser support for these CSS properties.


    Specify Word Breaking Rules

    You can also specify the line breaking rules for the text (i.e. how to break lines within words) yourself using the CSS3 word-break property.

    Values Accepted by the word-break property are: normalbreak-all and keep-all.

    Example

    p {
    
    width: 150px;
    padding: 10px;
    } p.break {
    background: #bedb8b;
    word-break: break-all;
    } p.keep {
    background: #f09bbb;
    word-break: keep-all;
    }
  • CSS3 Gradients

    Using CSS3 Gradients

    The CSS3 gradient feature provides a flexible solution to generate smooth transitions between two or more colors. Earlier, to achieve such effect we had to use the images. Using CSS3 gradients you can reduce the download time and saves the bandwidth usages. The elements with gradients can be scaled up or down to any extent without losing the quality, also the output will render much faster because it is generated by the browser.

    Gradients are available in two styles: linear and radial.

    Creating CSS3 Linear Gradients

    To create a linear gradient you must define at least two color stops. However to create more complex gradient effects you can define more color stops. Color stops are the colors you want to render smooth transitions among. You can also set a starting point and a direction (or an angle) along which the gradient effect is applied. The basic syntax of creating the linear gradients using the keywords can be given with:

    linear-gradient(direction, color-stop1, color-stop2, …)

    Linear Gradient – Top to Bottom

    The following example will create a linear gradient from top to bottom. This is default.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-linear-gradient(red, yellow);
    /* For Internet Explorer 10 */
    background: -ms-linear-gradient(red, yellow);
    /* Standard syntax */
    background: linear-gradient(red, yellow);
    }

    Linear Gradient – Left to Right

    The following example will create a linear gradient from left to right.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-linear-gradient(left, red, yellow);
    /* For Internet Explorer 10 */
    background: -ms-linear-gradient(left, red, yellow);
    /* Standard syntax */
    background: linear-gradient(to right, red, yellow);
    }

    Linear Gradient – Diagonal

    You can also create a gradient along the diagonal direction. The following example will create a linear gradient from the bottom left corner to the top right corner of the element’s box.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-linear-gradient(bottom left, red, yellow);
    /* For Internet Explorer 10 */
    background: -ms-linear-gradient(bottom left, red, yellow);
    /* Standard syntax */
    background: linear-gradient(to top right, red, yellow);
    }

    Setting Direction of Linear Gradients Using Angles

    If you want more control over the direction of the gradient, you can set the angle, instead of the predefined keywords. The angle 0deg creates a bottom to top gradient, and positive angles represent clockwise rotation, that means the angle 90deg creates a left to right gradient. The basic syntax of creating the linear gradients using angle can be given with:

    linear-gradient(angle, color-stop1, color-stop2, …)

    The following example will create a linear gradient from left to right using angle.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-linear-gradient(0deg, red, yellow);
    /* For Internet Explorer 10 */
    background: -ms-linear-gradient(0deg, red, yellow);
    /* Standard syntax */
    background: linear-gradient(90deg, red, yellow);
    }

    Creating Linear Gradients Using Multiple Color Stops

    You can also create gradients for more than two colors. The following example will show you how to create a linear gradient using multiple color stops. All colors are evenly spaced.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-linear-gradient(red, yellow, lime);
    /* For Internet Explorer 10 */
    background: -ms-linear-gradient(red, yellow, lime);
    /* Standard syntax */
    background: linear-gradient(red, yellow, lime);
    }

    Setting the Location Color Stops

    Color stops are points along the gradient line that will have a specific color at that location. The location of a color stop can be specified either as a percentage, or as an absolute length. You may specify as many color stops as you like to achieve the desired effect.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-linear-gradient(red, yellow 30%, lime 60%);
    /* For Internet Explorer 10 */
    background: -ms-linear-gradient(red, yellow 30%, lime 60%);
    /* Standard syntax */
    background: linear-gradient(red, yellow 30%, lime 60%);
    }

    Note: While setting the color-stops location as a percentage, 0% represents the starting point, while 100% represents the ending point. However, you can use values outside of that range i.e. before 0% or after 100% to get the effect you want.


    Repeating the Linear Gradients

    You can repeat linear gradients using the repeating-linear-gradient() function.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: white;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-repeating-linear-gradient(black, white 10%, lime 20%);
    /* For Internet Explorer 10 */
    background: -ms-repeating-linear-gradient(black, white 10%, lime 20%);
    /* Standard syntax */
    background: repeating-linear-gradient(black, white 10%, lime 20%);
    }

    Creating CSS3 Radial Gradients

    In a radial gradient color emerge from a single point and smoothly spread outward in a circular or elliptical shape rather than fading from one color to another in a single direction as with linear gradients. The basic syntax of creating a radial gradient can be given with:

    radial-gradient(shape size at position, color-stop1, color-stop2, …);

    The arguments of the radial-gradient() function has the following meaning:

    • position — Specifies the starting point of the gradient, which can be specified in units (px, em, or percentages) or keyword (left, bottom, etc).
    • shape — Specifies the shape of the gradient’s ending shape. It can be circle or ellipse.
    • size — Specifies the size of the gradient’s ending shape. The default is farthest-side.

    The following example will show you create a radial gradient with evenly spaced color stops.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-radial-gradient(red, yellow, lime);
    /* For Internet Explorer 10 */
    background: -ms-radial-gradient(red, yellow, lime);
    /* Standard syntax */
    background: radial-gradient(red, yellow, lime);
    }

    Setting the Shape of Radial Gradients

    The shape argument of the radial-gradient() function is used to define the ending shape of the radial gradient. It can take the value circle or ellipse. Here’s is an example:

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-radial-gradient(circle, red, yellow, lime);
    /* For Internet Explorer 10 */
    background: -ms-radial-gradient(circle, red, yellow, lime);
    /* Standard syntax */
    background: radial-gradient(circle, red, yellow, lime);
    }

    Note: If the shape argument is omitted or not specified, the ending shape defaults to a circle if the size is a single length, otherwise an ellipse.


    Setting the Size of Radial Gradients

    The size argument of the radial-gradient() function is used to define the size of the gradient’s ending shape. Size can be set using units or the keywords: closest-sidefarthest-sideclosest-cornerfarthest-corner.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: red;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-radial-gradient(left bottom, circle farthest-side, red, yellow, lime);
    /* For Internet Explorer 10 */
    background: -ms-radial-gradient(left bottom, circle farthest-side, red, yellow, lime);
    /* Standard syntax */
    background: radial-gradient(circle farthest-side at left bottom, red, yellow, lime);
    }

    Repeating the Radial Gradients

    You can also repeat radial gradients using the repeating-radial-gradient() function.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: white;
    /* For Safari 5.1 to 6.0 */
    background: -webkit-repeating-radial-gradient(black, white 10%, lime 20%);
    /* For Internet Explorer 10 */
    background: -ms-repeating-radial-gradient(black, white 10%, lime 20%);
    /* Standard syntax */
    background: repeating-radial-gradient(black, white 10%, lime 20%);
    }

    CSS3 Transparency and Gradients

    CSS3 gradients also support transparency. You can use this to create fading effects on background images when stacking multiple backgrounds.

    Example

    .gradient {
    
    /* Fallback for browsers that don't support gradients */
    background: url("images/sky.jpg");
    /* For Safari 5.1 to 6.0 */
    background: -webkit-linear-gradient(left, rgba(255,255,255,0), rgba(255,255,255,1)), url("images/sky.jpg");
    /* For Internet Explorer 10 */
    background: -ms-linear-gradient(left, rgba(255,255,255,0), rgba(255,255,255,1)), url("images/sky.jpg");
    /* Standard syntax */
    background: linear-gradient(to right, rgba(255,255,255,0), rgba(255,255,255,1)), url("images/sky.jpg");
    }
  • CSS3 Background

    Using CSS3 Backgrounds

    The CSS3 provides several new properties to manipulate the background of an element like background clipping, multiple backgrounds, and the option to adjust the background size.

    The following section will describe you all the new background features of CSS3, for other background related properties please check out the CSS background tutorial.

    CSS3 background-size Property

    The background-size property can be used to specify the size of the background images.  Prior to CSS3, the size of the background images was determined by the actual size of the images. The background image size can be specified using the pixels or percentage values as well as the keywords autocontain, and cover. Negative values are not allowed.

    Example

    .box {
    
    width: 250px;
    height: 150px;
    background: url("images/sky.jpg") no-repeat;
    background-size: contain;
    border: 6px solid #333;
    }

    Tip: The background-size property is typically used to create full size background images that scale according to the size of viewport or witdh of the browser.


    CSS3 background-clip Property

    The background-clip property can be used to specify whether an element’s background extends into the border or not. The background-clip property can take the three values: border-boxpadding-boxcontent-box.

    Example

    .box {
    
    width: 250px;
    height: 150px;
    padding: 10px;
    border: 6px dashed #333;
    background: orange;
    background-clip: content-box;
    }

    See the tutorial on CSS box model to learn more about element’s boxes.


    CSS3 background-origin Property

    The background-origin property can be used to specify the positioning area of the background images. It can take the same values as background-clip property: border-boxpadding-boxcontent-box.

    Example

    .box {
    
    width: 250px;
    height: 150px;
    padding: 10px;
    border: 6px dashed #333;
    background: url("images/sky.jpg") no-repeat;
    background-size: contain;
    background-origin: content-box;
    }

    Note: The background-origin property is ignored if the value of background-attachment property is specified as 'fixed'.


    CSS3 Multiple Backgrounds

    CSS3 gives you ability to add multiple backgrounds to a single element. The backgrounds are layered on the top of one another. The number of layers is determined by the number of comma-separated values in the background-image or background shorthand property.

    Example

    .box {
    
    width: 100%;
    height: 500px;
    background: url("images/birds.png") no-repeat center,  url("images/clouds.png")  no-repeat center, lightblue;
    }

    The first value in the comma-separated list of backgrounds i.e. the background-image ‘birds.png’ will appear on the top and the last value i.e. the ‘lightblue’ color will appear at the bottom. Only the last background can include a background-color.

  • CSS3 Color

    Defining Colors in CSS3

    In the previous section you’ve learnt how to define colors using the color keywords and RGB notations. In addition to that CSS3 adds some new functional notations for setting color values for the elements which are rgba()hsl() and hsla().

    In the following section we’ll discuss about these color model one by one.

    RGBA Color Values

    Colors can be defined in the RGBA model (red-green-blue-alpha) using the rgba() functional notation. RGBA color model are an extension of RGB color model with an alpha channel — which specifies the opacity of a color.

    The alpha parameter accepts a value from 0.0 (fully transparent) to 1.0 (fully opaque).

    Example

    h1 {
    
    color: rgba(0,0,255,0.5);
    } p {
    background-color: rgba(0%,0%,100%,0.3);
    }

    HSL Color Values

    Colors also can be defined the HSL model (hue-saturation-lightness) using the hsl() functional notation. Hue is represented as an angle (from 0 to 360) of the color wheel or circle (i.e. the rainbow represented in a circle). This angle is given as a unit less number because the angle is so typically measured in degrees that the unit is implicit in CSS.

    Saturation and lightness are represented as percentages. 100% saturation means full color, and 0% is a shade of gray. Whereas, 100% lightness is white, 0% lightness is black, and 50% lightness is normal. Check out the example below:

    Example

    h1 {
    
    color: hsl(360,70%,60%);
    } p {
    background-color: hsl(480,50%,80%);
    }

    Tip: By the definition red=0=360, and the other colors are spread around the circle, so green=120blue=240, etc. As an angle, it implicitly wraps around such that -120=240480=120, and so on.


    HSLA Color Values

    Colors can be defined in the HSLA model (hue-saturation-lightness-alpha) using the hsla() functional notation. HSLA color model are an extension of HSL color model with an alpha channel — which specifies the opacity of a color.

    The alpha parameter accepts a value from 0.0 (fully transparent) to 1.0 (fully opaque).

    Example

    h1 {
    
    color: hsla(360,80%,50%,0.5);
    } p {
    background-color: hsla(480,60%,30%,0.3);
    }
  • CSS3 Border

    Using CSS3 Borders

    The CSS3 provides two new properties for styling the borders of an element in a more elegant way — the border-image property for adding the images to borders, and the border-radius property for making the rounded corners without using any images.

    The following section will describe you these new border properties of CSS3, for other border related properties please check out the CSS border tutorial.

    Creating CSS3 Rounded Corners

    The border-radius property can be used to create rounded corners. This property typically defines the shape of the corner of the outer border edge. Prior to CSS3, sliced images are used for creating the rounded corners that was rather bothersome.

    Example

    .box {
    
    width: 300px;
    height: 150px;
    background: #ffb6c1;
    border: 2px solid #f08080;
    border-radius: 20px;
    }

    Adding CSS3 Border Images

    The border-image property allows you to specify an image to act as an element’s border.
    The design of the border is created from the sides and corners of the image specified in border-image source URL. The border image may be sliced, repeated, scaled and stretched in various ways to fit the size of the border image area.

    Example

    .box {
    
    width: 300px;
    height: 150px;
    border: 15px solid transparent;
    -webkit-border-image: url("border.png") 30 30 round; /* Safari 3.1-5 */
    -o-border-image: url("border.png") 30 30 round; /* Opera 11-12.1 */
    border-image: url("border.png") 30 30 round;
    }
  • CSS Validation

    Why Validate Your CSS Code

    As a beginner, it is very common that you will make mistake in writing your CSS code. Incorrect or non-standard code may cause unexpected results in how your page displayed or functions in a web browser.

    The World Wide Web Consortium (W3C) has created a great tool https://jigsaw.w3.org/css-validator/ to automatically check your style sheets, and point out any problems/errors your code might have, such as invalid CSS property missing closing bracket or missing semicolon (;) etc. It is absolutely free.

    Validating a Website

    Website validation is the process to ensure that the pages of a website conform to the formal guidelines and standards set by the World Wide Web Consortium (W3C).

    There are several specific reasons for validating a website, some of them are:

    • It helps to create Web pages that are cross-browser, cross-platform compatible. It also likely to be compatible with the future version of Web browsers and Web standards.
    • Standards compliant web pages increase the search engines spider visibility and your pages will more likely be appear in search results.
    • It will reduce unexpected errors and make your web pages more accessible to the visitor of your website.

    Note: Validation is important. It will ensure that your web pages are interpreted in the same way (the way you want it) by the various web browsers, search engines etc. as well as users and visitors of your Web site.

    Follow the link given below to validate your CSS document.

  • CSS Opacity

    Cross Browser Opacity

    Opacity is now a part of the CSS3 specifications, but it was present for a long time. However, older browsers have different ways of controlling the opacity or transparency.

    CSS Opacity in Firefox, Safari, Chrome, Opera and IE9

    Here is the most up to date syntax for CSS opacity in all current browsers.

    Example

    p {
    
    opacity: 0.7;
    }

    The above style rule will make the paragraph element 70% opaque (or 30% transparent).

    The opacity property takes a value a value from 0.0 to 1.0. A setting of opacity: 1; would make the element completely opaque (i.e. 0% transparent), whereas opacity: 0; would make the element completely transparent (i.e. 100% transparent).


    CSS Opacity in Internet Explorer 8 and lower

    Internet Explorer 8 and earlier version supports a Microsoft-only property “alpha filter” to control the transparency of an element.

    Example

    p {
    
    filter: alpha(opacity=50);
    zoom: 1;  /* Fix for IE7 */
    }

    Note: Alpha filters in IE accept values from 0 to 100. The value 0 makes the element completely transparent (i.e. 100% transparent), whereas the value 100 makes the element completely opaque (i.e. 0% transparent).


    CSS Opacity for All Browser

    Combining the both steps above you will get the opacity for all browsers.

    Example

    p {
    
    opacity: 0.5;  /* Opacity for Modern Browsers */
    filter: alpha(opacity=50);  /* Opacity for IE8 and lower */
    zoom: 1;  /* Fix for IE7 */
    }

    Warning: Including alpha filter to control transparency in Internet Explorer 8 and lower versions creates invalid code in your style sheet since this is a Microsoft-only property, not a standard CSS property.


    CSS Image Opacity

    You can also make transparent images using CSS Opacity.

    The three images in the illustration below are all from the same source image. The only differences between them are the level of their opacity.

    100% Opaque Image50% Opaque Image25% Opaque Image
    opacity:1opacity:0.5opacity:0.25

    Change Image Opacity on Mouse Over

    The following example demonstrates a common use of CSS image opacity, where the opacity of images changes when the user moves the mouse pointer over an image.

    — Move your mouse pointer over the images to see the effect.


    Text in Transparent Box

    When using opacity on an element not only the background of the element that will have transparency, but all of its child elements become transparent as well. It is making the text inside the transparent element hard to read if the value of opacity becomes higher.

    OPACITYOPACITYOPACITYOPACITY

    To prevent this either you can use transparent PNG images, or put the text block outside of the transparent box and push it visually inside using the negative margin or CSS positioning.

    Example

    div {
    
    float: left;
    opacity: 0.7;
    border: 1px solid #949781;
    } p {
    float: left;
    position: relative;
    margin-left: -400px;
    }

    CSS Transparency Using RGBA

    In addition to RGB CSS3 has introduced a new way RGBA to specify a color that includes alpha transparency as part of the color value. RGBA stands for Red Blue Green Alpha.

    The RGBA declaration is a very easy way to set transparency for a color.

    Example

    div {
    
    background: rgba(200, 54, 54, 0.5);
    } p {
    color: rgba(200, 54, 54, 0.25);
    }

    The first three numbers representing the color in RGB values i.e. red (0-255), green (0-255), blue (0-255) and the fourth representing alpha transparency value between 0 to 1 (0 makes the color fully transparent , whereas the value of 1 makes it fully opaque).

    One important characteristic to note about the RGBA transparency is that — the ability to control the opacity of individual color. With RGBA, we can make the text color of an element transparent and leave background intact.

    RGBARGBARGBARGBA

    — Or leave the text color alone and change only the transparency of background.

    RGBARGBARGBARGBA

    You can see how easily you can control the opacity of individual colors rather than the entire element using RGBA. However it is always recommended to define a fallback color for the browsers that do not support the RGBA colors.

    Note: The RGBA transparency doesn’t affect the child elements the way the opacity property does. The alpha value of RGBA affects the transparency of individual color rather than the entire element.


    Declaring a Fallback Color

    All browsers do not support RGBA colors. However, you can provide an alternative such as solid colors or transparent PNG images for the browsers that don’t support it.

    Example

    p {
    
    /* Fallback for web browsers that doesn't support RGBA */
    background: rgb(0, 0, 0);
    /* RGBa with 0.5 opacity */
    background: rgba(0, 0, 0, 0.5);
    }
  • CSS Sprites

    What is a Sprite

    Sprites are two-dimensional images which are made up of combining small images into one larger image at defined X and Y coordinates.

    To display a single image from the combined image, you could use the CSS background-position property, defining the exact position of the image to be displayed.

    Advantage of Using CSS Image Sprite

    A web page with many images, particularly many small images, such as icons, buttons, etc. can take a long time to load and generates multiple server requests.

    Using the image sprites instead of separate images will significantly reduce the number of HTTP requests a browser makes to the server, which can be very effective for improving the loading time of web pages and overall site performance.

    Note: Reducing the number of HTTP requests has the major impact on reducing response time that makes the web page more responsive for the user.

    Checkout the following examples and you will see one visible difference; when you place the mouse pointer over the browser icons in non-sprite version for the first time the hover image will appear after some time, it happens because the hover image is loaded from the server on mouse hover, since the normal and hover images are two different images.

    Whereas in sprite version, since all images are combined in a single image the hover image is displayed immediately on mouse hover that results in smooth hover effect.

    FirefoxChromeExplorerSafariOperaExample A
    FirefoxChromeExplorerSafariOperaExample B

    Using CSS sprite technique demonstrated in the: [EXAMPLE – B]; we were able to reduce the number of HTTP requests by 9 and the total file size of the image(s) by 38.2 KB as compared to the [EXAMPLE – A];. That’s a pretty huge improvement for such a small example. Imagine what you could do on a complete website.

    The whole process of creating this example is explained below.


    Making the Image Sprite

    We made this sprite image by combining 10 separate images in a single image (mySprite.png). You can create your own sprite using any image editing tool you like.

    Sprite Image Illustration

    Tip: For the sake of simplicity, we have used all icons of same size, and place them closely to each other for easy offset calculation.


    Display an Icon from Image Sprite

    Finally, utilizing CSS, we can display just the part of an image sprite we need.

    First of all, we will create the class .sprite that will load our sprite image. This is to avoid repetition, because all items share the same background-image.

    Example

    .sprite {
    
    background: url("images/mySprite.png") no-repeat;
    }

    Now, we must define a class for each item we want to display. For example, to display Internet Explorer icon form the image sprite the CSS code would be.

    Example

    .ie {
    
    width: 50px; /* Icon width */
    height: 50px; /* Icon height */
    display: inline-block; /* Display icon as inline block */
    background-position: 0 -200px; /* Icon background position in sprite */
    }

    Now the question arises, how did we get those pixel values for background-position? Let’s find out. The first value is the horizontal position, and second is the vertical position of background. As the upper-left corner of Internet Explorer icon touches the left edge so its horizontal distance from the starting point i.e. top-left corner of the image sprite is 0, and since it is placed on the 5th position so its vertical distance from the starting point of image sprite is 4 X 50px = 200px, because height of each icon is 50px.

    To show the Internet Explorer icon we have to move its upper-left corner to the starting point i.e. top-left corner of image sprite (mySprite.png). Also, since this icon is placed at the vertical distance of 200px, we will need to shift the whole background-image (mySprite.png) vertically up by 200px, which requires us to apply the value as a negative number that is -200px, because the negative value makes it go vertically up whereas a positive value would move it down. However, it doesn’t require a horizontal offset, since there are no pixels before the upper-left corner of the Internet Explorer icon.

    Tip: Just play around with the value of background-position property in the upcoming examples and you will quickly learn how the offsets work.


    Creating a Navigation Menu Using CSS Image Sprite

    In the previous section we have learned, how to display an individual icon from an image sprite. This is the easiest way to use image sprites, now we are going one step ahead by building a navigation menu with rollover effect as demonstrated in [EXAMPLE – B].

    Here we will use the same sprite image (mySprite.png) to create our navigation menu.

    Foundation HTML for Navigation

    We will start by creating our navigation menu with an HTML unordered list.

    Example

    <ul class="menu">
    
    &lt;li class="firefox"&gt;&lt;a href="#"&gt;Firefox&lt;/a&gt;&lt;/li&gt;
    &lt;li class="chrome"&gt;&lt;a href="#"&gt;Chrome&lt;/a&gt;&lt;/li&gt;
    &lt;li class="ie"&gt;&lt;a href="#"&gt;Explorer&lt;/a&gt;&lt;/li&gt;
    &lt;li class="opera"&gt;&lt;a href="#"&gt;Opera&lt;/a&gt;&lt;/li&gt;
    &lt;li class="safari"&gt;&lt;a href="#"&gt;Safari&lt;/a&gt;&lt;/li&gt;
    </ul>

    Applying the CSS on Navigation

    The following sections will describes you how to convert the simple unordered list given in example above to a spite image based navigation using the CSS.

    Step 1: Resetting the List Structure

    By default, HTML unordered lists are displayed with bullets. We’ll need to remove the default bullets by setting the list-style-type attribute to none.

    Example

    ul.menu {
    
    list-style-type: none;
    } ul.menu li {
    padding: 5px;
    font-size: 16px;
    font-family: "Trebuchet MS", Arial, sans-serif;
    }

    Step 2: Setting Common Properties for Each Links

    In this step we will set all the common CSS properties that all links are going to share. Such as, colorbackground-imagedisplaypadding, etc.

    Example

    ul.menu li a {
    
    height: 50px;
    line-height: 50px;
    display: inline-block;
    padding-left: 60px; /* To sift text off the background-image */
    color: #3E789F;
    background: url("images/mySprite.png") no-repeat; /* As all link share the same background-image */
    }

    Step 3: Setting Default State of Each Links

    Now, we must define a class for each menu item, because every item in the image sprite has different background-position. For example, Firefox icon is placed at the starting point i.e. top-left corner of the image sprite, so there is no need to shift the background-image. Hence the vertical and horizontal position of the background in this case would be 0. Similarly, you can define background-position for other icons within the image sprite.

    Example

    ul.menu li.firefox a {
    
    background-position: 0 0;
    } ul.menu li.chrome a {
    background-position: 0 -100px;
    } ul.menu li.ie a {
    background-position: 0 -200px;
    } ul.menu li.safari a {
    background-position: 0 -300px;
    } ul.menu li.opera a {
    background-position: 0 -400px;
    }

    Step 4: Adding Hover States of Links

    Adding hover states owns the same principle as adding the above links. Just move their upper-left corner to the starting point (i.e. top-left corner) of the image sprite as we have done above. You can simply calculate the background-position using the following formula:

    Vertical position of hover state = Vertical position of normal state - 50px

    As rollover images are just below the default state and height of each icon is equal to 50px. The hover state of icons also doesn’t require a horizontal offset, since there are no pixels before the upper-left corner of them.

    Example

    ul.menu li.firefox a:hover {
    
    background-position: 0 -50px;
    } ul.menu li.chrome a:hover {
    background-position: 0 -150px;
    } ul.menu li.ie a:hover {
    background-position: 0 -250px;
    } ul.menu li.safari a:hover {
    background-position: 0 -350px;
    } ul.menu li.opera a:hover {
    background-position: 0 -450px;
    }

    Done! Here is our final HTML and CSS code after combining the whole process:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Example of Sprite Navigation Menu</title>
    <style>
    
    ul.menu {
        list-style-type: none;
    }
    ul.menu li {
        padding: 5px;
        font-size: 16px;
        font-family: "Trebuchet MS", Arial, sans-serif;
    }
  • CSS Media Types

    Introduction to Media Types

    One of the most important features of style sheets is that, you can specify separate style sheets for different media types. This is one of the best ways to build printer friendly Web pages — Just assign a different style sheet for the “print” media type.

    Some CSS properties are only designed for certain media. For example, the page-break-after property only applies to paged media. However there are several properties that may be shared by different media types, but may require different values for that property. The font-size property for example can be used for both screen and print media, but possibly with different values.

    A document usually needs a larger font on a computer screen as compared to the paper for better readability, also sans-serif fonts are considered easier to read on the screen, while serif fonts are popular for printing. Therefore it is necessary to specify that a style sheet, or a set of style rules, applies to certain media types.

    Creating Media Dependent Style Sheets

    Three methods are commonly used to specify the media dependencies for style sheets:

    Method 1: Using the @media At-rules

    The @media rule is used to define different style rules for different media types in a single style sheet. It is usually followed by a comma-separated list of media types and the CSS declarations block containing the styles rules for target media.

    The style declaration in the example below tells the browser to display body content in 14 pixels Arial font on the screen, but in case of printing it will be in a 12 points Times font. However the value of line-height property is set to 1.2 for both of them:

    Example

    @media screen{
    
    body {
        color: #32cd32;
        font-family: Arial, sans-serif;
        font-size: 14px;
    }
    } @media print {
    body {
        color: #ff6347;
        font-family: Times, serif;
        font-size: 12pt;
    }
    } @media screen, print {
    body {
        line-height: 1.2;
    }
    }

    Note: Style rules outside of @media rules apply to all media types that the style sheet applies to. At-rules inside @media are invalid in CSS2.1.


    Method 2: Using the @import At-rules

    The @import rule is another way of setting style information for a specific target media — Just specify the comma-separated media types after the URL of the imported style sheets.

    Example

    @import url("css/screen.css") screen;
    @import url("css/print.css") print;
    body {
    
    background: #f5f5f5;
    line-height: 1.2;
    }

    The print media type in the @import statement instructs the browser to load an external style sheet (print.css) and use its styles only for print media.

    Note: All @import statements must occur at the beginning of a style sheet, before any declarations. Any style rule specified in the style sheet itself override the conflicting style rules in the imported style sheets.


    Method 3: Using the <link> element

    The media attribute on the <link> element is used to specify the target media for an external style sheet within the HTML document.

    Example

    <link rel="stylesheet" media="all" href="css/common.css">
    <link rel="stylesheet" media="screen" href="css/screen.css">
    <link rel="stylesheet" media="print" href="css/print.css">

    In this example the media attribute instructs the browser to load an external style sheet “screen.css” and use its styles only for screen while “print.css” for printing purpose.

    Tip: You can also specify multiple media types (each separated with comma e.g. media="screen, print") as well as media quires to the <link> element.


    Different Media Types

    The following table lists the various media types that may used to target different types of devices such as printers, handheld devices, computer screens etc.

    Media TypeDescription
    allUsed for all media type devices.
    auralUsed for speech and sound synthesizers.
    brailleUsed for braille tactile feedback devices.
    embossedUsed for paged braille printers.
    handheldUsed for small or handheld devices — usually small screen devices such as mobile phones or PDAs.
    printUsed for printers.
    projectionUsed for projected presentations, for example projectors.
    screenUsed primarily for color computer screens.
    ttyUsed for media using a fixed-pitch character grid — such as teletypes, terminals, or portable devices with limited display capabilities.
    tvUsed for television-type devices — low resolution, color, limited-scrollability screens, sound available.
  • CSS Pseudo-elements

    What is Pseudo-element

    The CSS pseudo-elements allow you to style the elements or parts of the elements without adding any IDs or classes to them. It will be really helpful in the situations when you just want to style the first letter of a paragraph to create the drop cap effect or you want to insert some content before or after an element, etc. only through style sheet.

    CSS3 introduced a new double-colon (::) syntax for pseudo-elements to distinguish between them and pseudo-classes. The new syntax of the pseudo-element can be given with:

    selector::pseudo-element { property: value; }

    These are the following most commonly used pseudo-elements:

    The ::first-line Pseudo-element

    The ::first-line pseudo-element applies special style to the first line of a text.

    The style rules in the following example formats the first line of text in a paragraph. The length of first line depends on the size of the browser window or containing element.

    Example

    p::first-line {
    
    color: #ff0000;
    font-variant: small-caps;
    }

    Note: The CSS properties that can be applied to the ::first-line pseudo-element are: font properties, background properties, color, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height.


    The ::first-letter Pseudo-element

    The ::first-letter pseudo-element is used to add a special style to the first letter of the first line of a text. The style rules in the following example formats the first letter of the paragraph of text and create the effect like drop cap.

    Example

    p::first-letter {
    
    color: #ff0000;
    font-size: xx-large;
    }

    Note: The CSS properties that can be applied to the ::first-letter pseudo-element are: font properties, text-decoration, text-transform, letter-spacing, word-spacing, line-height, float, vertical-align (only if ‘float’ is ‘none’), color, margin and padding properties, border properties, background properties.


    The ::before and ::after Pseudo-element

    The ::before and ::after pseudo-elements can be used to insert generated content either before or after an element’s content. The content CSS property is used in conjunction with these pseudo-elements, to insert the generated content.

    This is very useful for further decorating an element with rich content that should not be part of the page’s actual markup. You can insert regular strings of text or an embedded object such as image and other resources using these pseudo-elements.

    Example

    h1::before {
    
    content: url("images/marker-left.gif");
    } h1::after {
    content: url("images/marker-right.gif");
    }

    Pseudo-elements and CSS Classes

    Generally we need to style only a certain paragraph of text or other block-level elements with these pseudo-elements. That’s where declaring a class to the pseudo-element comes into play. The pseudo-elements can be combined with the CSS classes to produce the effect particularly for the elements having that class.

    The style rules in the following example will display the first letter of all paragraphs with the class="article", in green and size of xx-large.

    Example

    p.article::first-letter {
    
    color: #00ff00;
    font-size: xx-large;
    }