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 Linear Gradient – Left to Right The following example will create a linear gradient from left to right. Example 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 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 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 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 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 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: The following example will show you create a radial gradient with evenly spaced color stops. Example 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 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-side, farthest-side, closest-corner, farthest-corner. Example Repeating the Radial Gradients You can also repeat radial gradients using the repeating-radial-gradient() function. Example 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
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 auto, contain, and cover. Negative values are not allowed. Example 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-box, padding-box, content-box. Example 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-box, padding-box, content-box. Example 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 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 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 Tip: By the definition red=0=360, and the other colors are spread around the circle, so green=120, blue=240, etc. As an angle, it implicitly wraps around such that -120=240, 480=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
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 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
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. W3.org’s CSS Validator
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 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 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 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. opacity:1 opacity:0.5 opacity: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. OPACITY OPACITY OPACITY OPACITY 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 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 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. RGBA RGBA RGBA RGBA — Or leave the text color alone and change only the transparency of background. RGBA RGBA RGBA RGBA 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
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. FirefoxChromeExplorerSafariOpera FirefoxChromeExplorerSafariOpera 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. 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 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 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 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 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, color, background-image, display, padding, etc. Example 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 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 Done! Here is our final HTML
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 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 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 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 Type Description all Used for all media type devices. aural Used for speech and sound synthesizers. braille Used for braille tactile feedback devices. embossed Used for paged braille printers. handheld Used for small or handheld devices — usually small screen devices such as mobile phones or PDAs. print Used for printers. projection Used for projected presentations, for example projectors. screen Used primarily for color computer screens. tty Used for media using a fixed-pitch character grid — such as teletypes, terminals, or portable devices with limited display capabilities. tv Used 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 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 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 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
CSS Pseudo-classes
What is Pseudo-class The CSS pseudo-classes allow you to style the dynamic states of an element such as hover, active and focus state, as well as elements that are existing in the document tree but can’t be targeted via the use of other selectors without adding any IDs or classes to them, for example, targeting the first or last child elements. A pseudo-class starts with a colon (:). Its syntax can be given with: selector:pseudo-class { property: value; } The following section describes the most commonly used pseudo-classes. Anchor Pseudo-classes Using anchor pseudo-classes links can be displayed in different ways: These pseudo-classes let you style unvisited links differently from visited ones. The most common styling technique is to remove underlines from visited links. Example Some anchor pseudo-classes are dynamic — they’re applied as a result of user interaction with the document like on hover, or on focus etc. Example These pseudo-classes change how the links are rendered in response to user actions. Note: To make these pseudo-classes work perfectly, you must define them in the exact order — :link, :visited, :hover, :active, :focus. The :first-child Pseudo-class The :first-child pseudo-class matches an element that is the first child element of some other element. The selector ol li:first-child in the example below select the first list item of an ordered list and removes the top border form it. Example Note: To make :first-child to work in Internet Explorer 8 and earlier versions, a <!DOCTYPE> must be declared at the top of document. The :last-child Pseudo-class The :last-child pseudo-class matches an element that is the last child element of some other element. The selector ul li:last-child in the example below select the last list item from an unordered list and removes the right border from it. Example Note: The CSS :last-child selector does not work in Internet Explorer 8 and earlier versions. Supports in Internet Explorer 9 and above. The :nth-child Pseudo-class The CSS3 introduces a new :nth-child pseudo-class that allows you to target one or more specific children of a given parent element. The basic syntax of this selector can be given with :nth-child(N), where N is an argument, which can be a number, a keyword (even or odd), or an expression of the form xn+y where x and y are integers (e.g. 1n, 2n, 2n+1, …). Example The style rules in the example above simply highlight the alternate table row, without adding any IDs or classes to the <table> elements. Tip: The CSS :nth-child(N) selector is very useful in the situations where you have to select the elements that appears inside the document tree in a specific interval or pattern like at even or odd places, etc. The :lang Pseudo-class The language pseudo-class :lang allows constructing selectors based on the language setting for specific tags. The :lang pseudo-class in the example below defines the quotation marks for <q> elements that are explicitly given a language value of no. Example Note: Internet Explorer up to version 7 does not support the :lang pseudo-class. IE8 supports only if a <!DOCTYPE> is specified. Pseudo-classes and CSS Classes Pseudo-classes can be combined with CSS classes. The link with class=”red”, in the example below will be displayed in red. Example