Nested Styles

Suppose that you have a style that you want to apply to a particular tag but only when that tag is contained within another particular tag? We can handle this with stylesheets by using a nested tag definition. To nest tags we simply specify them one after the other separating them with spaces (and not commas). Here is an example

div div {background-color:red;}

The effect of this example is to turn the background of a div red but only if it is contained within another div.

The two tags that you are nesting don't have to be the same. Here is another example:

div p {color:red;}

This stylesheet code will turn all of the text contained within paragraphs red provided that those paragraphs are contained within a div.

Note that when you specify nested tags like this in your stylesheet definition that the code will not be applied at all unless the second tag is found within the first. You can of course extend this further by nesting more than two tags in your definition if you need to be even more specific.

Another thing to note about this way of defining styles is that the definition does not require that the second tag be contained directly within the first. Consider the following:

form input {float : right;}

Since input tags are required to be inside of a form anyway, the sole purpose of adding the reference to the form to the front of this line would be to make this command more specific than another one and so to override the float value specified elsewhere (perhaps for a specific definition for this page overriding the general definition used for the entire site).

Now an input tag is invalid if placed directly inside of a form tag and so there will generally be either a fieldset or div tag in between with the input tag inside the fieldset or div and that then inside the form. The CSS still works though without having to specify whether that intermediate level is a div is a fieldset because regardless of whether the input is nested inside a div or a fieldset, they are both nested inside the form tag.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow