Connect with us

CSS Advanced Tutorial

solution

CSS Advanced Tutorial

CSS ID vs CSS Class

CSS allows you to specify your own selectors called “id” and “class”. CSS Class and CSS ID allow you to structure and display your site and information the way you want. Class and ID names are both case sensitive. It is very important for you to know everything regarding ID vs. Class in CSS. This tutorial would also allow you to know about Div Class vs. ID.

CSS ID Selector

You can use ID selector, which is a CSS selector to stipulate a style for a single and unique element. It is also known as “Unique Identifier”. It uses ID attribute of the HTML element, and is defined with “#” (hash) in CSS document.

  1. #abc
  2. {
  3.     font-size:15px;
  4. }

CSS Class Selector

You can use CSS class selector to specify a style for a group of elements. Unlike the ID selector, the class selector is most often used on several elements. This allows you to set a particular style for any HTML element with the same class. The class selector uses the HTML class attribute, and is defined with “.” (dot).

  1. .abc
  2. {
  3.     font-size:15px;
  4. }

Differences

There are some basic differences between CSS ID and Class, they are:

  • ID must only be used for one element on a page; class can be used for many elements on a page.
  • ID can be used to select one item in JavaScript; class can be used to select multiple items in JavaScript.
  • ID selector can be called only once in a document (if ID is repeated on many places in HTML then it refers to first one), while a class selector can be called multiple times in a document.
  • An ID is identified in CSS using “#”. A Class is identified in CSS using “.”
  • An element can have multiple classes, but only one ID.

CSS ID Pros & Cons

PROS:

  • CSS ID can be used as a unique identifier for applying elements to a web page.
  • You can use the Document Object Model (DOM) to refer to CSS ID. It allows you to use JavaScript/DHTML techniques to build very interactive web sites.
  • It adheres more to HTML convention and fits into an HTML framework.

CONS:

  • ID can’t be reused.
  • ID can’t have multiple references like classes.
  • ID style can’t be modified by JavaScript (if ID is set dynamically).

CSS Class Pros & Cons

PROS:

  • It is easier to add special effects to multiple elements with a single declaration.
  • Have the ability to float elements to the left or right quickly.
  • It helps to simply maintain the uniformity in design, color and other elements of a web page.
  • It can be reused.
  • It can have multiple references.
  • It’s style can be modified by JavaScript.

CONS:

  • Class can’t be used as a unique identifier for applying elements to a web page.
  • It can’t be used as Document Object Model (DOM).
  • It conforms less to HTML conventions and framework.

CSS Float

You can use this property to specify whether or not a box should float and also if it should float left or to the right. You can use float basically like a text wrap that wraps images around with texts. However, it can also be used to manipulate the entire navigation and alignment of elements in a web page.

By using CSS float you can shift any element to the left or to the right as far as it can go. The non-floating content in the normal flow will flow around it on the opposite side. The float property is supported in all major browsers.

There are a number of values you can use for defining the float properties. The following table would clarify it even further.

SyntaxValueDescriptionApplies to
floatleftIt floats element to the leftAll Elements
floatrightIt floats element to the rightAll Elements
floatnoneThis is default and doesn’t float any elementAll Elements

  1. .setFloat
  2. {
  3.     float:left;
  4. }

If you are using floats, you will discover that the floats’ container doesn’t stretch up to accommodate the floats used in float-based layouts. If you simply need to add a border around floated element, you’ll have to command the browsers to stretch up the container to accommodate them. The solution to this problem is by clearing the float.

For clearing floats, you can use CSS Clear values like left, right, both and none. You can use “Both” which allows you to clear floats coming from either direction.

The Uses of Floats

There are a number of uses you can make of CSS float. They are:

  • You can use it with position relative.
  • A combination of float and display inline are used to convert unordered lists (<ul>) into horizontal menus or navigation tabs.
  • It has become easier to use divisions and CSS for creating multicolumn page layouts. The float property is one way to get division blocks to position similar to table cells.
  • You can create seo-friendly navigations with the help of CSS floats.
  • You can extensively use the float properties with JavaScript DOM.
  • CSS Float can be used to create printable CSS. The best thing is that it prints a web page exactly the way it is displayed on a computer screen.

CSS Display

You can use this property to specify the type of rendering box used for an element. In a language such as HTML where existing elements have well-defined behavior, default ‘display’ property values are taken from behaviors described in the HTML specifications. For Example, ‘<div>’, ‘<p>’, ‘<h1>’, ‘<ul>’, ‘<form>’ etc. are block level elements and ‘<span>’, ‘<a>’, ‘<b>’, ‘<strong>’, ‘<input>’, ‘<label>’, etc, are inline elements.

You can also hide an element by setting the display property to “none”. It hides the layout, but still affect the layout.

You can also change an inline element to a block element or vice versa. It will help you make the page look the way you want and still follow web standards. However, changing the display type of an element changes only how the element is displayed, Not what kind of element it is.

SyntaxValueDescriptionApplies to
displaynoneIt generates no box at allAll Elements
displayblockIt generates a block boxAll Elements
displayinlineIt generates an inline boxAll Elements
displayinline-blockGenerates a block box, laid out as an inline boxAll Elements

  1. .hideDiv
  2. {
  3.     display:none;
  4. }

The Uses of Display

There are a number of uses you can make of CSS Display, They are:

  • The CSS display property allows you to show or hide content using CSS and JavaScript. It shows or hides additional content with a simple click on a button. This is something that is used frequently in web pages and something that is worth learning.
  • The CSS display can also be used for making closeable DIVs. They are used for creating in-document messages and pop-up ads that come with a “close” option. This works with the use of “display: none” rule.
  • The CSS display property can be used for building dropdown menus. One can create beautiful dropdown menus by combining CSS’s display property and the :hover pseudo-class without a single line of JavaScript.
  • The CSS display property allows you to set up rules for display that make your content display as a grid or as if it were a table, when in fact the material is not a table.

CSS Clear

You can use CSS clear property to define which sides of an element’s box should remain clear from other floating elements. By using this, you can clear an element only from floated boxes within the same block. However, you can not clear the element from floated child boxes within the element.

The CSS clear property must be used after a float property on an element. CSS clear property is used to prevent the current element from remaining in the same horizontal band of floating elements. By default the value will be ‘none’.

There are a number of values you can use for defining the clear properties. The following table would clarify it even further.

SyntaxValueDescriptionApplies to
clearleftUse this for not allowing any floating elements on leftAll Elements
clearrightUse this for not allowing any floating elements on rightAll Elements
clearbothUse this for not allowing any floating elements on both left or & rightAll Elements
clearnoneUse this Default for allowing floating elements on both sidesAll Elements
clearinheritUse it to inherit clear property from the parent elementAll Elements

  1. .clearFix
  2. {
  3.     clear:both;
  4. }

The clear property almost supports all major browsers. However, “inherit” value is not supported in IE7 and earlier. Also remember; always match your clear to your float. If you have floated the element to the left, then you should clear to the left. Your floated element will continue to float, but the cleared element and everything after it will appear below it on the web page.

The most common way most designers use the clear property is in layout of page elements. For example, you might have an image floating inside a block of text and want the next paragraph to start below the image, or you might have an entire column of text that you want to float beside another bunch of text, with some text appearing below, this is when you can use css clear property.

The Uses of Clear

There are a number of uses you can make of CSS Clear. They are:

  • Can be used for clearing floating content.
  • Can be used to manage and control the flow of complete layout.
  • This can be used as ‘clearfix’ for managing DIV based/table less layouts and can be placed in a blank div or br tag.
  • It can be used for create or rectify box model layouts for creating proper borders or backgrounds height according to their contents.
  • Used to fix header, footer and sidebar related issues like overlapping layout elements.
  • Manipulate layout elements with it for better UI presentation.

CSS Cursor

You can use CSS cursor property for setting the type of cursor to be displayed for a pointing device. By changing the value of the cursor declaration you can assign cursor styles to various HTML elements. This property controls the type of cursor that is to be used when a pointing device is over an element.

You can set one value at a time only using this property. You can also set your own cursors just the way you want them by using CSS cursor property.

There are a number of CSS cursor property values that you can use. The following table would clarify it even further.

SyntaxValueDescriptionApplies to
cursorURLUse comma separated URL to custom cursorsAll Elements
cursorautoUse this default for allowing the browser to set a cursorAll Elements
cursorcrosshairUse it to render cursor as a crosshairAll Elements
cursordefaultUse the default CSS cursorAll Elements
cursore-resizeLet cursor indicate that an edge of a box is to be moved rightAll Elements
cursorhelpLet cursor indicate that help is availableAll Elements
cursormoveLet cursor indicate something should be movedAll Elements
cursorn-resizeLet cursor indicate an edge of a box to be moved upAll Elements
cursorne-resizeLet cursor indicate an edge of a box to be moved up and rightAll Elements
cursornw-resizeThe cursor indicates that an edge of a box is to be moved up and leftAll Elements
cursorpointerMake cursor render as a pointer (hyperlink pointer) and make it according to your useAll Elements
cursorprogressLet cursor indicate that the program is busyAll Elements
cursors-resizeLet cursor indicate an edge of a box to be moved downAll Elements
cursorse-resizeLet cursor indicate an edge of a box is to be moved down and rightAll Elements
cursorsw-resizeLet cursor indicate that an edge of a box to be moved down and leftAll Elements
cursortextLet cursor indicate textAll Elements
cursorw-resizeLet cursor indicate that an edge of a box to be moved leftAll Elements
cursorwaitLet cursor indicate that the program is busyAll Elements
cursorinheritUse this to inherit cursor property from a parent elementAll Elements

  1. .loading
  2. {
  3.     cursor:wait;
  4. }

The cursor property is supported in all major browsers. Although the CSS spec says that this property is inherited, there are some exceptions in browsers. Some elements that use a different default cursor will override the parent cursor type by default unless explicitly set to ‘inherit’.

The Uses of Cursor

There are a number of uses you can make of CSS cursor property. They are:

  • It can be used to create windows like web applications or web pages.
  • It allows you to define cursor as busy when page is opening.
  • You can create rich web based user interfaces for editing or cropping images, resizing panels, etc. with the help of JavaScript.
  • It can be used for creating color picker tools using JavaScript.
  • It allows you to define your own custom cursors; the file extension is normally “.cur”.

CSS Outline

You can use CSS outline property, which is a property for setting outline in CSS. CSS outline properties set the color, style, and width of an outline by using different CSS outline property values. You can also use outline, its shortcut property to set them all in one declaration. One need not set all the properties separately. However, in that case omitted properties will automatically be set to default values.

There are a number of CSS outline property values that you can use for defining the outline properties. The following table would clarify it even further.

SyntaxValueDescriptionApplies to
outlinestyle,
color,
width or
none
Shortcut for setting all outline properties in one declarationAll Elements
outline-colorcolorUse it to define the color of the outline through color name, hex color code or RGB valueAll Elements
outline-stylestyleIt allows you to specify the style (border) of the outlineAll Elements
outline-widthwidthSet the width of the outline using thisAll Elements

  1. a
  2. {
  3.     outline:solid #ff0000 2px;
  4. }

An outline is a line that is drawn around elements, outside the border edge, to make the element “stand out”. However, it is different from the border property. The outline is not a part of the element’s dimensions; therefore the element’s width and height properties do not contain the width of the outline. The outline property is normally supported in all major browsers. However, it is not supported in IE6 and Netscape browsers.

The Uses of Outline

There are a number of uses you can make of CSS outline property. They are:

  • It can be used for styling and decorating layouts and works almost like CSS border.
  • You can use it to change the formatting of a hyperlink’s outline that appears when you click on it.
  • It can be created outside the CSS padding and CSS margins of the elements.
  • It is also used when the web page is browsed by using keyboard “tab” key, the link area selected by pressing the tab key is called outline of that element. It can be disabled as well.

CSS Visibility

You can use CSS visibility property to define whether an element should be visible or not. You can also use it to hide and display text and other elements. You must remember that even if a box in the normal flow is set as a hidden, it will still influence the layout of other elements.

However, the source code still contains whatever is in the invisible paragraph. From seo purpose, you must make sure that your source code contains all the information that needs to be indexed by the search engines.

There are a number of values you can use for defining the visibility properties. The following table would clarify it even further:

SyntaxValueDescriptionApplies to
visibilityvisibleUse this default for making the element visibleAll Elements
visibilityhiddenMake an element invisible using this as it keeps the spaceAll Elements
visibilitycollapseUse this only for table elementsAll Elements
visibilityinheritinherit the visibility property from the parent elementAll Elements

  1. div.vis
  2. {
  3.     visibility:hidden;
  4.     width:200px;
  5.     height:150px;
  6. }

CSS visibility almost supports all major browsers. However, not a single version of Internet Explorer supports the “inherit” or “collapse” values. Also remember, invisible elements in CSS visibility property elements cover the space on the page. Here one must use CSS Display and Visibility properties together to solve this problem. You should use “display” property to create invisible elements that do not consume the space.

Related:  PHP script to prevent Google AdSense click bombing

The Uses of Visibility

There are a number of uses you can make of CSS visibility property. They are:

  • It can be used for hiding the content. It works almost same like “CSS display” property but the container is not hidden in this scenario. (It hides only the content part).
  • You can use it for creating CSS tabs, CSS menus or other interactive things by using some JavaScript.
  • You can use it to creating closeable DIVs.
  • You can use it for showing or hiding validation messages while using HTML forms.
  • It can be used for building dropdown menus.

CSS Z-Index

You can use, Z-Index CSS Property to specify the stack level of a box whose position value is either absolute, fixed, or relative. You can use CSS z-index property to layer elements in front or behind each other.

The stack level generally means the position of the box along the z axis. It normally stays vertical to the display. Moreover, as the value gets higher, the box comes closer to the user.

There are a number of values you can use for defining the CSS z-index properties. The following table would clarify it even further.

SyntaxValueDescriptionApplies to
z-indexautoUse this default to set the stack order equal to its parentsAll Elements
z-indexnumberUse it to set the stack order with integers. Positive and negative integers are allowed.All Elements
z-indexinheritDefine whether z-index should be inherited from the parent elementAll Elements

  1. .layer
  2. {
  3.     z-index:100;
  4.     width:200px;
  5.     position:absolute;
  6. }

Additionally, z-index CSS only works on positioned elements. They generally work in all major browsers. The CSS z-index influences the stack order in both block-level and inline elements. You can declare them by a positive or negative integer value, or a value of auto.

Z-index uses values to identify which element is more important then the other. The default value is normally 0. Off course, the numbers you give to the Z-index does not really play an important role. The most important thing you should remember is that your top item should be of the highest value. Just make sure that, experiment and use Z-index to your advantage.

The Uses of Z-index

There are a number of uses you can make of CSS z-index. They are:

  • You can use z-index for creating overlapping tabbed navigation.
  • It can be used for creating layers with positioning.
  • It is mainly used for creating and managing pop ups, dropdown menus, etc.
  • Used for creating rich user interface like Ajax based pre-loaders which appears over the content.
  • Used for creating transparent non clickable layer for whole page.
  • The z-index property can be used as part of a CSS-based tooltip.
  • Can be used to create light boxes.
  • One can also use z-index for creating unique photo gallery effects.
  • One can create fancy social bookmarking boxes using Z-index as well.

CSS Overflow

This property you can use to specify the behavior that occurs when an element’s content overflows the element’s box. It allows you to create a window of text or an image within your web page even if it’s too big for the page. The overflow declaration tells the browser what to do with content that doesn’t fit in a box.

The default behavior keeps the overflowing content visible. However, you are allowed to change it. You can use the CSS Overflow property to clip a content within an element’s box. You also have the option of scrolling the content.

You can apply overflow property to the body or HTML elements in an HTML document.

In case a scrollbar needs to be provided, you need to place it between the element’s outer padding edge and its inner border edge. The space occupied by the scrollbar should be subtracted from the computed width or height, so that the inner border edge is preserved. Boxes with an overflow value other than visible will expand vertically to enclose any floated descendant boxes. Margins will never collapse for a box with an overflow value other than visible.

SyntaxValueDescriptionApplies to
overflowvisibleNot clipped and renders outside the element’s box. This is defaultAll Elements
overflowhiddenIt’s clipped and the rest of the content is invisibleAll Elements
overflowscrollIt’s clipped but a scroll-bar is added for other content visibilityAll Elements
overflowautoIt’s clipped but a scroll-bar is needed to see other contentAll Elements

  1. .scrollDiv
  2. {
  3.     overflow:scroll;
  4.     height:100px;
  5. }

The Uses of Overflow

There are a number of uses you can make of CSS Overflow, They are:

  • The CSS overflow property allows you to create scrollable content area. It is a section that can contain any type of content like text, image or whatever you want, that can be scrolled through. Such scrollable areas are a convenient way to present your data and organize it. They can be very useful when you feel you must have everything on your home page.
  • The CSS overflow property can also be used for text trimming. This will put the whole text and simply hide the part of the text that is longer than the div. So, if you increase your browser resolution, the browser will automatically display more or less of the text.
  • The CSS overflow property can be used with max-height/min-height or max-width/min-width properties for making it more user friendly

CSS Position

This property allows you to change how elements are positioned on your webpage. The CSS position propety has four main values, they are:

  • absolute
  • fixed
  • relative
  • static

To use CSS position absolute, you’ll need to define any two of either top or bottom, and either left or right. If none of those four are specified then a default of 0 is given to the top and left properties. An absolutely positioned element is positioned relative to the first parent element that has a position other than static applied to it. If no parent element meets the condition, then the element is positioned relative to the document window.

First the fixed positioned element is always positioned relative to the browser window. They are rebel position and are not influenced at all by their parents or user declarations.

You can use position: relative syntax to make the elements overlap each other as a relatively positioned element. It makes it move into the space occupied by the other neighboring elements and create a ghost like effect.

CSS position static is the default. If you apply the position: static syntax, there will be a normal document flow. A statically positioned element will ignore any values for the properties, top, right, bottom, and left as well as any z-index declarations. You can only apply this property if your element has absolute, relative, or fixed positioning applied.

SyntaxValueDescriptionApplies to
positionabsoluteCreates absolutely positioned element, and works like layer.All Elements
positionfixedCreates an absolutely positioned element, positioned relative to the browser window.All Elements
positionrelativeCreates a relatively positioned element, positioned relative to its normal positionAll Elements
positionstaticIt is by default and creates no position at all.All Elements

  1. .scrollDiv
  2. {
  3.     position:absolute;
  4.     width:100px;
  5.     top:30px;
  6.     left:80px;
  7. }

The Uses of Position

There are a number of uses you can make of CSS Position, They are:

  • The CSS position property allows you to create Tableless layouts. This can be done by cropping the main division on the sides using the margin-left and margin-right properties, and then to position each side columns using position:absolute, and set the top left corner and top right corner coordinate to (0,0).
  • The CSS position property and especially absolute positioning can be used for creating side columns, but only if they will always be shorter than the main content column.
  • The CSS position property can be used to create Vertical or side navigations. You can do this by placing a statically positioned list inside of a floated or absolutely positioned column, then turning off the bullets and changing the margins on padding on the list items.
  • You can create inline statically positioned elements by using CSS position property. If you statically position the list items, they are turned into inline elements. Then you can style them using background colors and borders to create the desired effect.
  • You can also create drop-down menus using CSS Position. You can use a combination of relativel or absolute position to make sure that the drop-down portion can be properly aligned with the content or the entire page.

CSS Hacks

Table of Contents

There are numbers of techniques for using CSS Hacks smartly, following are some of the most popular techniques:

  • An Introduction to CSS Hacks
  • Conditional Comments
  • CSS !important
  • CSS Hacks for IE
  • PNG Hack

An Introduction

CSS hacks is the most apt way to tackle browser inconsistencies. They take advantage of browser bugs to perform magic such as “hiding” CSS Rules from specific Web Browsers, or kicking browsers that don’t follow the specs into line.

There are multiple CSS browser hacks you can use. But it is important to know about how the CSS hacks & browser detection works. The browser detection is done by sending one CSS rule to the browser(s) you’re trying to trick, and then by sending a second CSS rule to the other browsers, overriding this first command.

If you have two CSS rules with identical selectors then the second CSS rule will always take precedence. The first command is intended for IE, the second for all other browsers. By inserting a CSS hack we can perform our browser detection by hiding the second CSS rule from IE. This means that IE won’t even know it exists and will therefore use the first CSS rule.

Conditional Comments

Among all browsers, Internet Explorer (IE) maintains the worst level of standards support. That is why, there are a number of CSS hacks available for different versions of IE. Fortunately, till version 5, it supports a rather safe-to-use hack called “conditional comments”.

Conditional comments use a special syntax. This syntax includes HTML markup wrapped in a conditional statement. It is further placed within an HTML comment. There are two forms of conditional comments: positive and negative. If the statement evaluates to true, the enclosed HTML is revealed within the HTML document. If the statement evaluates to false, the enclosed HTML remains hidden. Because conditional comments are placed with HTML comments, the enclosed HTML also remains hidden from all browsers that don’t support conditional comments.

The following snippet will clarify the point even more:

For all IE Versions:

  1. <!–[if IE]>
  2.   <link href=”ie.css” type=”text/css” rel=”stylesheet” />
  3. <![endif]–>

For IE 6 Version Only:

  1. <!–[if IE 6]>
  2.   <link href=”ie6.css” type=”text/css” rel=”stylesheet” />
  3. <![endif]–>

For less than IE 6 Version:

  1. <!–[if lt IE 6]>
  2.   <link href=”ie6-less.css” type=”text/css” rel=”stylesheet” />
  3. <![endif]–>

For less than or equal to IE 6 Version:

  1. <!–[if lte IE 6]>
  2.   <link href=”ie6-less-equal.css” type=”text/css” rel=”stylesheet” />
  3. <![endif]–>

For greater than IE 6 Version:

  1. <!–[if gt IE 6]>
  2.   <link href=”ie6-greater.css” type=”text/css” rel=”stylesheet” />
  3. <![endif]–>

For greater than or equal to IE 6 Version:

  1. <!–[if gte IE 6]>
  2.   <link href=”ie6-greater-equal.css” type=”text/css” rel=”stylesheet” />
  3. <![endif]–>

Conditional comments have certain parameters that it follows for different versions of IE, they are:

lt: less than
lte: less than or equal to
gt: greater than
gte: greater than or equal to

You can define conditional comments for particular version as well which includes IE 5, 6, 7 or 8.

!important

This means that the styles are applied in order as they are read by the browser. CSS rules marked !important take precedence over later rules. Normally in CSS the rules work from top to bottom, so if you assigned a new style to an element further down the style sheet or in a secondary style sheet then the later rule would take precedence. !important ensures that this rule has precedence.

The following snippet will clarify the point better:

  1. .abc
  2. {
  3.     font-size:15px !important;
  4. }

CSS Hacks for IE

There have always been the problem with Internet Explorer implementing CSS commands differently compared to other more standards compliant browsers. However, where there is a problem, there is a solution as well. CSS hacks for different IE versions are the perfect remedy for this. However, different browsers have different bugs and different fixes.

IE 6Internet Explorer 6 isn’t perfect, but unfortunately the user base for the outdated browser is still high. IE6 actually does keep the html CSS object as the child of something else, contrary to the standard and there the problem lies. However, to solve this problem you can use CSS underscore hack (” _ “) that IE6 tends to read and process as a valid CSS property.

  1. .IE6-Font
  2. {
  3.     font-size:15px; _font-size:18px;
  4. }

IE 7Internet Explorer 7 is better than IE6, but there are still many CSS related inconsistencies such as IE7 Div problem, IE7 width problem etc. The CSS underscore hack doesn’t work here as it is W3C compliant. However, you can use CSS hash hack (#) to fix all CSS related inconsistencies in IE7.

The following snippet will clarify the point better:

  1. .IE7-Font
  2. {
  3.     font-size:15px; #font-size:18px;
  4. }

IE 8Internet Explorer 8 is no doubt a superior browser compared to IE7, but there are still CSS compatibility issues like rendering problems and table width/height display problems etc. To solve that you can use font-size/*\**/:15px\9; and fix most of the CSS inconsistencies prevailing in IE8.

Apart from that, it also works in all versions less than IE 8, you only need to define it first before applying IE7 and IE6 hacks like font-size/*\**/:15px\9; #font-size:13px; _font-size:14px;.

The following snippet will clarify the point better:

  1. .ieHacks
  2. {
  3.     font-size/*\**/:15px\9; #font-size:13px; _font-size:14px;
  4. }

PNG Hack

When you place a PNG with variable transparency on to the page and check that out in a IE6 browser, you’will surely get shocked. IE6 renders any pixel that requires transparency as a grey mess. Earlier, we would have suggested you to add a wrapper around the image with the exact dimensions of the image or to add a class of “ie-hide”. However, now we would suggest you to use CSS PNG hacks (but it creates problem for link).

This amazing CSS hack adds near-native PNG support with alpha opacity to IE 5.5 and 6. Now you can have full transparency and no more ugly grey borders. It also supports full CSS background positioning and repeat including CSS sprites. It requires only one line in your CSS file, and no changes to your website HTML.

The following snippet will clarify the point better:

  1. .pngHacks-4-ie6
  2. {
  3.     filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’
  4.     /images/menu-tp-bg.png’, sizingMethod=’crop’);

CSS Opacity

An Introduction

This is a really important CSS topic today. This is surely influenced by the design trends that typified the web2.0 movement. The CSS opacity property allows you to modify the transparency of any element on your web pages, from images to colored boxes. This makes CSS opacity an extremely useful way to guide your user’s attention to the important parts of your web pages, improving the user experience.

It has been around for few years but still not a standard CSS property. There are different methods of setting CSS opacity for different elements of a web page on different browsers. There are many types of opacity like CSS background opacity, CSS text opacity, CSS DIV opacity, CSS menu opacity and more. One can also try CSS opacity cross browser for cross browser influence. Opacity is specified by W3C in the CSS Color Module Level 3 Working Draft.

Opacity in IE (Internet Explorer)

Since Internet Explorer have never become fully compatible with CSS, it needs different transparency settings all together compared to all other browsers. These settings are different for all major IE versions like IE6, IE7 and IE8 and sometimes even require additional CSS to make them functional. All CSS opacity related information with IE you can find below:

Opacity in IE6In IE6, CSS uses the proprietary filter property that is filter:alpha(opacity=50) to enable transparency. However, the transparency settings only work when the element applied to “have layout”. filter: progid:DXImageTransform.Microsoft.Alpha(opacity=40) is another proprietary filter that works in IE6.

The following example will clarify the point more:

  1. .opaDiv
  2. {
  3.     filter:alpha(opacity=50);
  4. }

Opacity in IE7Just like IE6 in IE7 also uses filter: alpha(opacity=50) CSS filter property. The Explorer Windows requires it to make it work in IE7. The element must have layout for this filter to work. You can also create layout for the element to implement the transparency settings on it. filter: progid:DXImageTransform.Microsoft.Alpha(opacity=40) also works in IE7.

Related:  Best WooCommerce WordPress Themes

The following example will clarify the point more:

  1. .opaDiv
  2. {
  3.     filter:alpha(opacity=50);
  4. }

Opacity in IE8Internet Explorer 8 uses -ms-filter: “progid:DXImageTransform.Microsoft.Alpha(opacity=40) CSS filter property. You must have noticed that there are two main code differences between IE6 or IE7 with IE8 CSS filter property. A “-ms-“ prefix is attached to the filter property, and there are certain quotations around the entire value declaration, both of which are necessary for that syntax to work.

NOTE: If somebody wants to apply the CSS Opacity in all versions of IE, then he must specify IE8 opacity as first compared to IE6 or IE7.

The following example will clarify the point more:

  1. .opaDiv
  2. {
  3.     -ms-filter:“progid:DXImageTransform.Microsoft.Alpha(opacity=40)”;
  4.     filter:alpha(opacity=40);
  5. }

CSS Opacity in Other Browsers

For setting CSS opacity for other browsers, you can use the syntax opacity: .7;. This will ensure that there is 70% opacity . If the setting of opacity is : 1 it will result into an opaque element. On the other hand, if the opacity setting is : 0, then the element will be completely invisible. You only need to remember that the lower the opacity the closer you’ll be to transparency. Although, the opacity property can be set to two decimal places like “.01”, however it is better to use one decimal place value like “.1”.

The following example will clarify the point more:

  1. .scrollDiv
  2. {
  3.     opacity:.7;

CSS Sprites

CSS Sprites Explained

This technique allows you to create a single file that contains all the images laid out in a grid, requiring only a single image and only a single server call with roughly the same file size because the empty space is compressed. In that file, you will place all individual “sprites” that make up your interface separated by enough space that they don’t start running over each other. You’ll then set the background position (using negative values to move the background up) and include enough space around each sprite so that only it appears in the background of the element, effectively masking the rest of the sprite images.

How Do They Work?

It splices together multiple images in one larger image and then displays different sections of the image. CSS Sprites uses simple CSS scripting. In the style sheet, the element is given various :hover and :active properties, similar to a link. The properties define which part of the image is displayed when a site user hovers or clicks on the image. This technique is most commonly used to display changing images like navigation buttons and images that utilize rollovers.

To use sprites, you need to create a new image that is as wide as your widest image and and as tall as the combined height of all your images plus X pixels, where X is the number of images you have. Now place your images into this new image, left aligned, one on top of the other with one pixel of white space in between.

The following example will clarify the point more:

CSS Sprites Image:
Here we are using only one single image with all icons.

Output:
For using css sprites image, we need to define those icons with css background position.

  1. .spritesDiv
  2. {
  3.     background:url(images/img-css-sprites.png) -10px -50px no-repeat;
  4. }

Here, Background position -10px stands for left position and -50px stands for top position.

Why Should You Use CSS Sprites?

Using CSS sprites will speed up your website loading time and thus improve performance and user experience. By using CSS Sprites you can increase the accessibility of your webpages significantly as they load in split seconds.

Instead of loading images one after one, you load a single large image that contains all images used in your website. Therefore, there are less HTTP-Requests and the page loads faster.

There are a certain benefits of using CSS Sprites:

  • Fewer images for the browser to download, which means fewer requests to the server.
  • Total images size is generally smaller, so less download time for the user and less bandwidth consumption.
  • No mouseover code, no JavaScript , only CSS.

What are They Used For?

There are some major points for using CSS Sprites:

  • You can use CSS Sprites for creating a free flowing navigation for a website. These kind of navigation allows a user to quickly browse different web pages and help to enhance the popularity and accessibility to a website.
  • You can also use them to create Image Rollovers. You can now quickly and easily use single images and CSS sprites to create easy image rollovers and pre-loading hover images.
  • You can use them for compressing the image size in your website and optimize your website for fast loading in less bandwidth conditions as well.
  • You can use CSS background sprites to set the background for a web page also. It can be tiled horizontally and vertically both.

CSS Media

This property allows you to change how documents will be presented in different media. You can display a document differently on the screen, on paper, on mobile, on TV etc. The CSS media propety has some important values, they are:

SyntaxValueDescriptionApplies to
mediaallUsed for all media type devicesAll Elements
mediaauralUsed for speech and sound synthesizersAll Elements
mediahandheldUsed for small or handheld devicesAll Elements
mediaprintUsed for printersAll Elements
mediaprojectionUsed for projected presentations, like slidesAll Elements
mediascreenUsed for computer screensAll Elements
mediattyUsed for media using a fixed-pitch character grid, like teletypes and terminalsAll Elements
mediatvUsed for television-type devicesAll Elements

By default, stylesheets apply to all media types. You can use either of three ways to make styles apply only to specific CSS media types. The first is to use the media attribute of the link or style tag. This accepts media types in a comma separated list.

You can also use the media type ‘all’ to signify that the stylesheet is for all media types. This is the same as not supplying a media attribute.

  1. <head>
  2. <link href=”URL.css” rel=”stylesheet” type=”text/css” media=”all” />
  3. </head>

The second way to specify a media type is to use the @media rule. This allows you to add media specific sections inside your stylesheet so you can use a single stylesheet, and still provide styles for specific media types. The @media rule is similar to the media attribute; it accepts a comma separated list. This rule can be put anywhere inside your stylesheet (they can even be nested), and should contain relevant style rules inside curly braces. Any styles not inside a @media rule are applied to all media types:

CSS media import is also an option that allows you to import an already created stylesheet having media types defined. But it is outdated now and these days nobody is using it.

  1. <style type=”text/css”>
  2. @media print
  3. {
  4. .myDiv
  5.   {
  6.     font-size:15px;
  7.   }
  8. }
  9. </style>

The Uses of Media

There are a number of uses you can make of CSS Media, They are:

  • The CSS media property allows you to create a printer-friendly page without actually building one. You can create CSS media print stylesheet that removes all the non-friendly options on your page and even takes into account issues such as typography and readability.
  • The CSS media type allows you to build Web applications that take into account how users may use or view your site. It allows you to tailor content for certain media types via style sheets and test them before the actual release.
  • You can also use CSS media queries to style your CSS media iPhone, CSS media iPad for improving the experience of users visiting your website from an iPhone. The CSS queries allow you to evaluate how your content will display on these devices.

CSS Optimization

CSS optimization is a must in today’s cut-throat competitive world. There are trillions of websites running across the globe and everyone is looking to offer the best user experience. This is very important, as no one likes to spend much time in browsing your site and wait for the page to refresh in hours. Therefore, no matter how good looking, informative the website is, the audience will leave you and never come back.

This tutorial is all about the different CSS optimization techniques, CSS optimization tricks and some CSS optimization tips. Pay attention to the below given sections for a detailed understanding.

Seek Help from Your CSS Shorthand Buddy

Use CSS shorthand to reduce the amount of code contained in a CSS document. This will surely optimize your CSS files and decrease their size significantly. It will further help you generate more efficient code for faster page downloads. This is a really cost-effective approach for achieving cost-effective website acceleration. CSS shorthand makes it even easier for you to style your markup, and helps you code faster and in a consistent manner.

  1. .short
  2. {
  3.     padding:10px 5px 8px 15px;
  4.     font:bold 12px/18px arial,verdana;
  5.     color:#f00;
  6.     background:url(myimage.png) #ffffff 0px 0px no-repeat;
  7. }

There’s No Scope For White Spaces/Line-Breaks

The white spaces and line breaks are something that we normally ignore in our CSS files. However, these extra white spaces and line breaks add a lot of bytes to the overall file size of the website. This is why it is advisable that one should make proper use of them without leaving any unnecessary space or line break in the CSS file.

Once coding is done in such a manner, rectifying the mistakes can be really tough. So, it is better to keep this in mind while coding it in the first place.

The following example will clarify the point further:

  1. .short
  2. {
  3. padding:10px 5px 8px 15px;font:bold 12px/18px arial,verdana;color:#f00;
  4. background:url(myimage.png) #ffffff 0px 0px no-repeat;
  5. }

Merge Multiple CSS and Stay Ahead

Merging multiple CSS files is a great way to optimize CSS files existing in a website. This guarantees all the files will be called at once enabling the pages to load fast. However, you can combine them together and then optimize that single large file using some compression tool also. This will reduce the total CSS file size of the website significantly. Unfortunately, if you try to do this manually you are going to run into maintenance problems.

The following example will clarify the point further:

  1. <head>
  2. <link href=”URL0.css” rel=”stylesheet” type=”text/css” media=”all” />
  3. <link href=”URL1.css” rel=”stylesheet” type=”text/css” media=”all” />
  4. <link href=”URL2.css” rel=”stylesheet” type=”text/css” media=”all” />
  5. </head>

Merge multiple CSS in one CSS only, for this you can merge manually or can merge dynamically with programming:

  1. <head>
  2. <link href=”Global.css” rel=”stylesheet” type=”text/css” media=”all” />
  3. </head>

Forget Internal/Inline CSS, Use External Only

Do not use internal or inline CSS as they make JavaScript and CSS inlined in HTML documents to get downloaded every time the HTML document is requested. It is advisable to use external CSS files for faster pages because the JavaScript and CSS files are cached by the browser. This guarantees reduced HTTP requests without increasing the size of the HTML document. However, if you put the JavaScript and CSS files in external files and get cached by the browser, the size of the HTML document decrease significantly without increasing the number of HTTP requests.

The following example will clarify the point further:

Internal CSS

  1. <head>
  2. <style type=”text/css”>
  3. .myclass
  4. {
  5. font:bold 12px/18px arial,verdana;
  6. }
  7. </style>
  8. </head>

Inline CSS

  1. <body>
  2. <div style=“font:bold 12px/18px arial,verdana;“></div>
  3. </body>

Instead of using above styles, use external stylesheet like:

  1. <head>
  2. <link href=“myCSS.css” rel=”stylesheet” type=”text/css” media=”all” />
  3. </head>

Let Gzip/deflate Compress Your CSS For Good

Gzipping generally reduces the response size by about 70%. Approximately 90% of today’s Internet traffic travels through browsers that claim to support gzip. It reduces response times by reducing the size of the HTTP response. When lighter contents travel from server side to client side and vice versa, the process gets faster.

If you use Apache, the module configuring gzip depends on your version: Apache 1.3 uses mod_gzip while Apache 2.x uses mod_deflate.

The following example will clarify the point further:

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

You can also use this deflate compression in your .htaccess file on server root.

Play Smart with CSS Class Names

Calling multiple classes by creating a common class name in an element allows you to optimize your CSS significantly. The common class name repeats itself in many classes in your CSS file and allows you to call it according to your need in any HTML element.

For example: “float:left” and “font-size:12px;” almost repeats in many classes so we can make a separate class name for “.fl-left{float:left;}” and “.font12{font-size:12px}” and can do the same thing with other class names as well. Finally, we can call both classes in the same element “<div class=’fl-left font12′>”.

Therefore, create common class names for repeated classes and enjoy some optimized CSS making your website fast, user-friendly and highly accessible.

  1. <body>
  2. <div class=“floatLeft Setfont txt“></div>
  3. </body>

Conclusion

The above discussed CSS optimization techniques will surely help you create fast loading websites with better usability and optimum accessibility. It will result to satisfied users sometimes even boosting your return on investment. Always remember one equation:

CSS Optimization Techniques = Happy Browsing

Surely, this is the most appealing tutorial to you, if the assumption is correct. It’s very important to know about using CSS and it’s even more important how to optimize it for the best results. So, don’t miss to check out our next chapter for something even more exciting and useful.

CSS Don’t’s

Think Twice Before Using CSS Expression

CSS expressions are a powerful way to set CSS properties dynamically. They’re supported in Internet Explorer, starting with version 5. However, there is one big problem. The expression method accepts a JavaScript expression. The CSS property is set to the result of evaluating the JavaScript expression. Not only are they evaluated when the page is rendered or resized, but also on slightest of scrolling and movement of mouse over the page. Moving the mouse around the page can easily generate more than 10,000 evaluations.

As a result, it has some fatal drawbacks, they are:

  • The page keeps refreshing
  • Requires high bandwidth for consistent performance
  • Such websites are never user-friendly
  • Often result in no display or basic HTML views without images

Don’t Dig your Own Grave by Using Inline CSS

Inline styles are CSS styles that are applied to one element using the style attribute. Inline styles, despite offering more control to a user, are not the best way to maintain your Web site. They cause problems and you can only use them if you want to check a style quickly during development.

There are many drawbacks of using inline CSS, they are:

  • Inline styles only affect the exact tag they are applied to and do not separate content from design.
  • Inline styles are very difficult to maintain. it can be really tough to find out where a style is being set. A website is normally created with a mixture of inline, embedded, and external styles and there finding it becomes even tougher.
  • Inline styles are not accessible and not SEO friendly.
  • They make web pages bigger and heavier requiring high bandwidth consumption.

Never Use Repeated Property and Useless CSS Classes

Using repeated property and useless classes in CSS just make the page heavier. As a result, it doesn’t load fast and hamper the accessibility of the website a great deal. Therefore, it is advisable to avoid unnecessary CSS classes and repetition of different properties.

Conclusion

All the above discussed points are absolutely no for CSS. They can create a number of problems and has many drawbacks. So, you should completely avoid using them. However, on the contrary you should do certain things for best CSS results with CSS Optimization.

This tutorial must have put you on high alert regarding the Don’t’s of CSS. Follow us till our next chapter and we will surely offer you another interesting advanced CSS tutorial.

Continue Reading
You may also like...

We are a WordPress plugin developer company that focuses on useful WordPress plugin creation and empowering people to earn passive incomes from their blogs. We build unique and groundbreaking plugins that will revolutionize your blog!

Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *

More in solution

    Sign up for our newsletter and get a free affiliate e-book!

    About Me:

    Szabi Kisded

    Hi, my name is Szabi and I'm documenting my journey earning an online (semi)passive income. Learn more

    Mega Plugin Bundle:

    CodeCanyon Portfolio:

    Online Courses:

    Recommended Theme:

    Popular Posts:

    Latest Posts:

    To Top