Basic css selectors. CSS selectors


Today we'll look at the concept of CSS selectors and how we can use them to shorten our HTML markup, making it cleaner.

CSS selector– this is the element to which we are going to apply CSS properties. The word "selector" is self-explanatory; it means choice.

P (color: red) div span (background: green) ul li (list-style: none)

Class and id selectors

In the example above we have 3 selectors - p, div span, ul li. That is, our entire style file consists of selectors and their properties. It is most convenient and intuitive, especially for beginners, to use the class name of the tag or the unique identifier of the tag as the selector. To assign a class or identifier to any tag, we must specify it among the attributes of that tag. A specific tag can have a maximum of 1 ID and infinite number classes. Example:

text in first div
text in second div
text in third div

What you should pay attention to:

  • Classes and identifiers can be assigned to any (all) tags.
  • Each id is unique and cannot be repeated within the same page, unlike classes!
  • The same class can be assigned to any tags and can be repeated any number of times on a page.
  • If we want to assign several classes to a specific tag, we simply specify them separated by a space.
  • The names of classes and identifiers can be the same, but apart from the name, there will be nothing in common between them.

How to refer to a class or id in a stylesheet (CSS) file?

Let's look at an example:

#first (color: red;) /* access the id named first */.second (color: blue;) /* access the class named second */#first .second (color: orange;) /* access the class named second ONLY if it is INSIDE the tag with identifier first */.first .third (color: grey;) /* refer to the class named third ONLY if it is INSIDE a tag with class first */

In our case, the last two instructions will not work, since we do not have classes nested inside tags with given attributes. As you may have noticed, to indicate that we are referring specifically to id, we need to put a hash sign (#) in front of its name without spaces; if we are referring to a class, then we must put a dot (.) in front of the class name.

Using classes and identifiers is very convenient, but it increases our HTML markup, ideally (which never exists) we should not use them at all, instead we will use combinations and groupings of selectors, the rest of the article will be about them, but! But this does not mean at all that you should completely abandon the use of classes and identifiers, you just should keep in mind that very often, instead of creating a new class or id, you can get by with the techniques described below and they can also be quite convenient.

What is the difference between class and id?

In addition to the above differences, it is also worth noting that properties specified by id have a higher priority than properties assigned to the class. That is, if we write:

text in diva

Then the text color will become red, despite the fact that the class is lower in the code and if they had equal priority the text would turn blue.

According to the syntax: in cases with a class, we can choose which tag should have this class, for this, after the tag name WITHOUT a space, we must refer to the class. Example:

Myclass (properties) /* will apply to all tags that contain the class myclass */ div.myclass (properties) /* will only apply to div tags that contain the class myclass */

This will also work for id, but such an entry is meaningless, since id cannot be repeated on the page, which means it is enough to simply declare the id without the tag to which it refers:

text

There seems to be only one unspecified difference left, and it concerns a topic that I did not plan to touch on in the near future on this blog - Javascript. But I am still obliged to report it to you: if you want to access an element with using Javascript, then for this purpose it will be very convenient to have an id for this element. To refer to an element by its class in Javascript there is no such built-in feature, you will have to use secondary functions+ it's not always cross-browser compatible.

Bottom line: we use id and class, but in moderation, always asking ourselves whether it is possible to do without them and how advisable it is.

Related selector

Div p (color: green;) /* Selector by child */ p(color: red;) /* selector by tag */

But as I already wrote in the previous article, in the first case, CSS properties will be applied to all p tags nested at ANY depth of the div tag. But what if we want to apply properties only to direct descendants, that is, to the first level of nesting:

Third level

Direct heir (first level)

Second level

Direct heir (first level)

In this case, we must use the so-called related selector, an angle bracket is used to denote it, you can use spaces or you can leave them out, I would not recommend it:

Div>p (color: blue;) /* only the first level of nesting */ div p (color: blue;) /* absolutely all paragraphs inside a div */

Universal selector

We've sorted this out, we already have 3 types of selectors in our arsenal, now I want to tell you about a very unusual selector that stands out among all the others - this is the so-called universal selector, which is indicated by an asterisk (*):

* (margin: 0; padding: 0;)

This is how everyone starts for me new project, I advise you to do the same. The universal selector applies to all page elements (tags), but has zero priority (below only no priority at all). It is commonly used to override the CSS properties that browsers set by default for some tags. Imagine, this actually happens! Browsers set their own properties for quite a few tags by default, for example, the hyperlink tag blue text color and underlining, they set padding to the body tag, etc. There is absolutely no need for us to remember, know and use this, so we immediately remove the most banal properties using a universal selector, however, I would not recommend adding anything else to it (or adding, but carefully), despite the smallest (null ) priority of the universal selector, in some cases it can still override other properties for you, so keep that in mind.

By the way, when working with selectors, as with any work related to layout layout, it is very convenient to use viewing page elements. If you are not yet aware of such things as Opera Dragonfly, Firebug and web inspectors in general, then, without exaggeration, you urgently need to read the article at the link above! And whoever has already used similar things, please follow me.

Pseudo-classes

Unlike classes, pseudo-classes do not need to be specified in the HTML markup; they are calculated by the browser themselves. We have 4 static pseudo-classes and 3 dynamic pseudo-classes, excluding CSS 3, more on that towards the end. Static ones include (:first-child, :link, :visited, :lang()):

Direct heir (first level)

Third level

Direct heir (first level)

Second level

Direct heir (first level)

Result:

Naturally, you can combine selectors as you wish, for example:

Div>span p:first-child (color: green;) /*will work if p is the first child of its parent and is inside a span tag that is a direct child of a div tag */

The name of the pseudo-class presented above speaks for itself first-child - the first child.

The following two static pseudo-classes apply only to the hyperlink tag (:link, :visited), they apply CSS properties depending on whether the this link specific user or not:

A:link (color: blue;) /* set the color blue for unvisited links, and by default they are underlined */ a:visited (color: green; text-decoration: none;) /* visited links will have red text, remove the underlining */

The pseudo-class:lang() is used to provide different styling depending on the language. The language to which the design should be applied is indicated in brackets. This can be used, for example, to specify different styles of quotes in quotes:

Q:lang(de) (quotes: "\201E" "\201C";) /* quotes for German */ q:lang(en) (quotes: "\201C" "\201D";) /* quotes for English */ q:lang(ru) (quotes: "\00AB" "\00BB";) /* quotes for Russian language */

This is perhaps the only possible type of selector that I have never used.

Dynamic pseudo-classes

Dynamic pseudo-classes are :active, :hover, :focus. Dynamic pseudo-classes are triggered by a specific action on the page, they work for all tags, and not just for links, as many people think and even claim in their blogs! Let's consider their application:

P:active (background: red;) /* style that will be applied to the tag when you click on it (mouse click) */ input:focus (width: 400px;) /* style that will be applied to the element on which this moment focus (works, for example, for text input fields: textarea, input). IN in this case upon focusing, the width of the input will become equal to 400 pixels, convenient to use for beautiful effect Extend the field by clicking. */ div:hover (background: green;) /* Triggered when the cursor hovers over an element, mainly used to create a beautiful effect when hovering over links. */

Apply these styles to our example above and you will see for yourself.

Adjacent selectors

Adjacent selectors are the nearest neighbor below the code, not the child! Very convenient selector:

text in paragraph of first div

text in paragraph OUTSIDE div

text in paragraph of second div

text in span

again the paragraph is outside the div

Result:

Generalized adjacent selectors

Generalized adjacent selectors act exactly like regular adjacent selectors, except that the properties apply not just to the first neighbor below, but to all specified neighbors below:


text in diva

paragraph

paragraph

paragraph


text in span

paragraph

paragraph


paragraph in diva

paragraph in diva


text in span

paragraph

Result:

Attribute selectors

Attribute selectors allow us to access tags that have the attribute we need, or even a specific value:

P (properties) /* apply to all p tags that have an align attribute */ p (properties) /* where the value of the align attribute is center */ p (properties) /* where the value of the align attribute starts at center */ p (properties) /* where the value of the align attribute contains center */ p (properties) /* where site can be among other words separated by spaces () */ p (properties) /* where the value of the class attribute consists only of or begins with the word site, followed by a hyphen and the rest of the value ( or ) */ p (properties) /* where the value of the align attribute ends with center */

CSS 3 pseudo-classes

You have already become familiar with all the main selectors and this should be enough for you in the first couple of days. However, in CSS 3, many new pseudo-classes have appeared, now we can take not only the first child, but also any other child, we can go from the opposite, take not the first, but the last child, and so on and so forth. All this is very convenient and practical, except that you may have problems with older versions of IE. Let's gather all our strength and go through all the remaining selectors, so that later you can keep them in mind when creating your own layout.

:last-child – analogous to:first-child, but takes not the first, but the last child.

:only-child – will work if the element (tag) is the only child.

:only-of-type - will work if the element (tag) is the only child of its type.

:nth-child() – refers to children by their serial numbers, you can access all even or odd numbers. For example:


paragraph

paragraph

paragraph


text in span

paragraph

paragraph

paragraph

paragraph

paragraph

paragraph

Result:

:nth-last-child – works the same as the previous one, but the report starts from the end.

:first-of-type – the first child of its type within the direct parent.

:last-of-type – the last child of its type within the direct parent.

:empty – will work for those tags that do not contain a single character (no text).

:not() – throws an exception for the given elements. Example:


paragraph with class roll


paragraph

paragraph


paragraph with class roll

Result:

Managing fields, forms, radio buttons, and checkboxes in CSS

:enabled - applies to accessible interface elements such as forms, buttons, switches, etc. By default, all interface elements are accessible.

:disabled - applies to disabled interface elements such as buttons, forms, and so on. Interface elements are disabled if you add the disabled attribute to them in HTML or disabled="disabled" in XHTML.

:checked – applies to interface elements such as radios and checkboxes when they are in the on position.

Pseudo-elements

Pseudo-elements, similar to pseudo-classes, are calculated automatically by the browser; we don’t need to worry about this. To avoid confusing pseudo-elements with pseudo-classes in CSS specs 3, it was decided to use a double colon, instead of a single one, as was the case in CSS 2. Therefore, on the Internet you can find pseudo-elements with both a single colon and a double colon - both options are correct. However, for better compatibility with IE, it is recommended to use a single colon.

:first-line – the first line inside a block or table element.

:first-letter – the first letter inside a block element.

Bottom line: now you know and can use the full power of cascading style sheets, but this does not mean that you need to immediately rush to create website layouts using as many selectors, pseudo-classes and pseudo-elements as you have learned today. I have listed all the possible tools, and you should choose only the most necessary for yourself.

Benefits of optimizing HTML with CSS

Part of the point of all of the above is to move away from the ubiquitous use of class and id attributes in HTML, thereby leaving everything to the mighty style sheets.

External style files, like external Javascript files are perfectly cached, which means that when visiting any page of your site for the first time, the user’s browser remembers these files and does not download them again, unlike the site page itself, that is, your HTML markup, pictures and text, which the browser downloads again and again. The same goes for search engines, they don’t care about yours at all. external files, but they don’t care about the volume and content of your HTML markup. Search engines you have to scan the entire structure of the page and in your own interests help them with this, focus their efforts on the content, and not on a cumbersome wall of markup consisting of a bunch of classes and identifiers, or worse - Javascript event handlers and CSS styles directly in tag attributes (and such still happens).

You can argue with me, they say, we can force the client browser to download local environment all included files, pictures, cache the entire page, and so on and so forth. Against such a background, such a trifle is completely lost, but one way or another, by reducing the HTML markup as much as possible, you only win, without losing anything except a possible habit.

Let's summarize: thanks to optimization and reduction of HTML, we have a very small gain in site loading speed and SEO ( search engine optimization), as well as cleaner code.

Since we don't want to style all our HTML elements at once, we need the ability choose a subset of these elements.

CSS selectors determine which elements we want to apply the style to.

Basic tag selectors

Targeting basic HTML tags is easy: just use the tag name.

There is a direct connection between the name HTML tag and the CSS selector used.

Classes

Given that we probably don't want to style all paragraphs or all headings the same, we need to differentiate them.

Of all HTML attributes class attribute is the most important for CSS. It allows you to determine group HTML elements that we can precisely target. Just put a dot before the name of the class you want to use:

Date ( color: red; )

On the other hand there is HTML attribute class with the value date . It must match the CSS class name.

You can use any name for your class, but it must not start with a number.

The .date class selector will target all HTML elements with a class="date" attribute. So the following HTML elements All will be styled:

The event will take place in Saturday.

Please note that the tag name doesn't matter, only the class attribute is taken into account.

Identifiers

You can also use the id attribute in your HTML and define it in your CSS using a hash:

#tagline( color: orange;)

This title will be orange.

Identifiers are similar to classes in that they are also based on an HTML attribute.

Example

Combining selectors

Let's use our previous example in which we want to make our dates red:

The event will take place in Saturday.

If we want our dates inside instead were displayed in blue? We can add the following CSS rule:

Em.date ( color: blue; )

em.date combines:

  • em tag selector;
  • class selector .date .

It will only apply to elements . This will not affect other .date or .

Selector Hierarchy

A space in the selector defines the ancestor/child relationship. Let's say we want the links in our header to be red:

Header a ( color: red; )

Pseudo-classes

HTML elements can have different states. The most common case is when you hover over a link. It is possible in CSS to apply a different style when such an event occurs.

Pseudo-classes are bound to regular selectors and begin with a colon.

This material is devoted to the basics of styling on an Internet resource using selectors.

Selectors in CSS are used to define a specific
element in the html page for which you need to apply
or change the CSS style.

Types of selectors in CSS

Element selector

To give the necessary CSS style, in this case the name is written as a selector html element. For example, it is enough to specify the desired style for the H1 heading, after which these headings will take the form we require. This is what the code will look like:

H1 (
font-size: 11pt;
}

There are often times when you need to make headings in different styles. Here, a class selector will help solve this problem.

Selector by class

The class selector is universal in CSS. You can write it as follows: before the name of the class we write a dot, and only then in curly brackets we indicate the style we need:

.red (
font-family: tahoma, sans-serif;
color:red;
font-size: 11pt;
}

An example of using a class selector. Apply this style to the H1 heading in html page:

Page title

From the example above you can see that the "class" attribute with the given name is applied CSS style "red".
Another example. In the html part we write:

This header is blue because the corresponding class is applied to it


id".

In the html document it will look like this:

Let's set the style for this paragraph

In the CSS document:

p#newstyle ( color: blue; font-size: 12px;)

As a result, a blue font with a size of 12px will be used for this paragraph.

Context selector

An equally necessary component is context selector.
For example, on a website there was a need for “H1” headings, enclosed with the tag bold highlight in red:

H1 bold ( color:red ; )

As you can see, the H1 heading is written first, a space is added, the tag bold and then in brackets the style we specified. This can be expressed in words like this: “If there is a bold tag inside the H1 header, the text should be red.”

In this way, you can also set styles for items in bulleted lists, tables, and even their cells, with different levels of nesting.

Next page -

CSS selectors are one of the main features of the CSS language. Selectors allow you to access either a group of elements or just one of them.

Selectors in CSS

Selectors are used to tell the browser which elements to apply the styles described in curly braces.

P(Styles…)

In this case, the selector is p – paragraph tag. This rule will add styles to all paragraphs on a web page.

What are the types of CSS selectors?

Tag selector - the simplest. It has been demonstrated in an example. To write it in css, you need to write the tag name without angle brackets. The styles will be applied to all elements with that tag.
Table() – styles for all tables
Li() – styles for all list items
A() – styles for all links

Style class– you can attach a style class to any element on a web page. Even to one letter. Then in the css file you can access this element by writing your own styles for it. To do this, you need to put a dot and write the name of the style class after it. Examples:
.about() – the rules will apply to all elements that have the class = "about" attribute
.down() – the rules will be applied to all elements that have the class = "down" attribute
.float() – the rules will apply to all elements that have the attribute class = "float"

As you can see, the main thing is to make a point. A style class can be bound to an unlimited number of elements. An element can be assigned several classes.

Identifier– another type of selector. One identifier can be assigned to only one element. It cannot have two identifiers, and the id associated with this element cannot be registered anywhere else.

It is set like this:

Paragraph

That is, just like a class, only the attribute is used id any word is used as its meaning.

To access an element with an identifier via css, you need to write the id value and put a hash in front of it.

#first( Font-size: 22px )

We turned to the paragraph with id = first. The style will only be applied to it. For the remaining paragraphs, the font size will not change.

Pseudo-classes

There is one interesting type of selector in CSS: pseudo-classes. That is, classes that elements have by default and do not need to be specified additionally. Some of them only work for links, while some can be applied to all elements. In any case, CSS pseudo-classes greatly facilitate the work of a web developer.

A pseudo-class is a style class of an element that we didn’t actually define ourselves, it just exists on its own. For example, seeing this code in html:

Paragraph

You can absolutely tell that this paragraph has a special class, because it is written there. But pseudo-classes do not need to be written; elements have them by default, and this is their advantage in this case. Next, let's look at the most popular of them.

For links

For input fields and links

:focus – The style is applied to the element that receives input focus.
In fact, there are a lot of new cool pseudo-classes for input fields, but they are all new to CSS3, and in this article I would like to discuss only the simplest ones. There will definitely be an article about CSS3 selectors in the future.

For all elements

  1. :hover – style applied when hovering over an element
  2. :first-child – select the first child element
  3. :last-child – last child element
  4. :nth-child() – A number or formula is written in parentheses that determines which elements will be selected.
  5. :first-of-type, :last-of-type, :nth-of-type() – work almost identically to the previous pseudo-classes. The only difference is that the element type is taken into account here. The difference can be felt in the following example:
    li:first-child – the first list item will be selected, but only if the li element comes first in the parent block. If there is another tag before it, nothing will be selected.
  6. li:first-of-type – the first list item from all that is in the parent will be selected. It doesn't matter where they are located in the code. I hope the difference is clear.
  7. :nth-last-child – works similar to :nth-child, but counts from the last element, not the first.
  8. :nth-last-of-type – similar to :nth-last-child, but taking into account the element type.

These are not all pseudo-classes, but the most popular and necessary ones. Actually, all pseudo-classes are marked in the same way in css, separated by a colon. In addition, you can combine selectors and get interesting features:
a:visited:active – styles for the already visited link that is clicked on.
div:first-child:hover – styles for all the first blocks in their parents that are hovered over.

As you can see, such selectors provide great opportunities in terms of styling elements. Use them and you can easily reach any elements.

Combining selectors

Another important rule you need to know about. Style class selectors can be written without separating them from each other. For example:
.class1.class2 – will select those elements that have both of these classes.
.class1.class3.class8 – will select elements to which all three style classes are attached.

Nested selectors

If we separate selectors from each other with spaces, we can reach the element we need. Examples:
Table td – selects all cells in tables
Ul li a – selects all links located in list items (and list items, in turn, lie in the lists themselves)
.class1 p – will select all paragraphs with the attribute class = “class1”
.class2 p span – will select all tag contents , lying in paragraphs with class class2.

You can nest and combine in this way as many times as you like. Examples:
#header .logo span:first-letter()– selects the first letter in the span of the logo, which is located in the header
.class1.class2:hover() – will define the hover style for elements that have both style classes.

Child selectors

If you need to style parent elements that are DIRECTLY subsidiaries, then you need to write it like this:
Ul > li() – will select list items that are nested directly in it, and not in other tags
P > a() – will select only those links in paragraphs that lie directly within them, and not nested in other tags (which, in turn, are already nested in paragraphs)
Example:

If you write a selector like this P > a , will the styles be applied to the link in the example above? No, because it is still nested in another tag, that is, it is not a direct child.

Adjacent selectors

The last thing we'll look at today. If you write it in css like this:
.class1 + .class4() , then this selector will select the element with the attribute class = "class4" , and this element must appear in the HTML code immediately after the element with the class class1. Only in this case everything will work. Let's look at an example again:

Will the above selector (.class1 + .class4()) work? No, because the elements are not next to each other. Between them is the img tag. If you remove it, then everything will work.

So, we have looked at the most basic and simplest selectors. Surely this knowledge will be enough for you to solve 95% of problems. In the next article I will describe some more specific CSS selectors.

Attribute selectors

Allows you to select specific elements without assigning a style class or identifier to them.

Attribute selectors are those selectors in which an attribute or an attribute with a value is written in square brackets. A few examples to make it clear:
* – selects all elements that have an href attribute with any value.
input – selects all input elements that have a disable attribute (all disabled fields).
input – selects all fields whose type is password , that is, fields for entering a password.
img – selects an image that has the src attribute = "/logo.png" specified.

As you can see, writing CSS attribute selectors is not that difficult. Their most important difference is the square brackets, in which either just an attribute or an attribute with its exact value is written. But the functionality of these selectors does not end there.

Advanced css attribute selectors

All of the following selectors are case sensitive.
Search at the beginning of a line
div – selects all divs that have a style class starting with "block" . Thus, for example, the following blocks will be selected: "block-head", "block-3", "blocknote" . The main thing is that there is a keyword at the beginning of the meaning.

Finding at the end of a line
A – selects all links whose address ends in .rar . Thus, if you can download something on your website, then you can add an icon next to all links to archived files.

Finding a substring everywhere in a value
span – will select all span tags that have “art” in their class name anywhere in the name. Thus, for example, spans with the following classes will be selected: party, clart, art-1.

Search for prefixes
p – will select paragraphs with a style class that have a name that either exactly matches “first” or that contains the prefix first- that begins the class name.

Finding words within meaning
input– will select all input elements in which the value of the identifier attribute contains the word text . It differs from searching for a substring everywhere in that it is the word that must be included, not the substring.

The last two options are rarely used and are unlikely to be useful to you often, but for general development you can still know about them.

What are attribute selectors useful for?

Using such selectors, you can select many HTML elements without giving them style classes. In some cases, using this method you can shorten the code and simplify your work. For example, above I gave an example with an icon for archives. Here another idea appeared. For example, on your website you often link to one other resource (Wikipedia, say) and you want to display a special icon next to links to Wikipedia, which other links should not have.

You can implement it like this:

A (css rules)

In fact, there are many more ways to use attribute selectors. They can to some extent simplify the work where it is needed. Use css and subscribe to the blog to learn more about web development.

Css3 selectors and pseudo classes

About new css3 selectors, which I didn’t write about in previous articles.

Improved work with forms

These are new pseudo-classes. Basically they all concern new possibilities of forms.
:enabled – the pseudo-class will select all active fields. That is, those in which you can write something or are at least readable.
:disabled is the opposite pseudo-class, selects all disabled fields. Accordingly, with its help you can add additional styles to such fields.
:read-only – select all input, which are read-only.
:read-write – selects all fields that are editable.

Adding styles with validity in mind

There are also very interesting pseudo-classes with which you can assign styles depending on the validity or invalidity of the entered value. Previously, this could only be done using JavaScript.
:valid – selects all fields in which the entered value satisfies the requirements. The requirements themselves are usually specified using the pattern attribute. May also depend on the field type. For example, a field containing an email address will be considered invalid if there is no @ in the entered value.
:invalid – accordingly, selects all invalid fields in which the value does not correspond to what is expected. For example, you can make the text color in fields like this red:

Input:invalid( Color: red; )

Now if we write incorrect values ​​in the fields, the text turns red. Accordingly, you can also use pictures of a checkmark and a cross to show the user whether he filled out everything correctly.

Styles for required fields

I would also like to note that the corresponding pseudo-class has appeared for required fields.
:required – will select elements that have this attribute. That is, all fields are required to be filled out.
:optional – the opposite class, will select fields that are optional.

Pseudo-class:not

:not is a kind of anti-selector that allows you to determine which elements DO NOT USE styles. A couple of examples.
A:not(:last-child)() – will select all links on the page except the last one.
.nav:not(li)() – will select all elements with class nav, but these should not be list items (li).
#article p:not(.special:first-child) – will select all paragraphs in the article block except the first paragraph with the special class.

As you can see, a condition is written in parentheses for the pseudo-class: what exactly needs to be excluded from the selection. You can also write combination selectors in the condition, so you can select and exclude anything you want.

This is the pseudo-class that is sometimes needed, it is needed not only in theory, but also in practice. Oh yes, you can also continue composing the selector after :not(). For example:
Div:not(#header) .wrap – selects all divs with the wrap class, except the div with id = "header"

These were selectors that were introduced in CSS3.

Priority of css selectors

To determine which styles take precedence, use these simple rules:
ID is the highest priority selector. If an element has a style class and an id , and both are assigned the same properties with different values, then the styles written for the id will be executed.

The class is a higher priority selector than the tag selector (p, table, ul). A pseudo class has the same weight as a simple class. p:first-line takes precedence over .firstline because the second selector is just a class, while the first is a tag selector + pseudo-class.

Another useful rule is that the more specific the selector, the more prioritized styles are for it. For example, between body and p, the paragraph wins the battle because it is a more specific selector than body (because it is the entire page, so not very specific). Table p , in turn, is more specific than just p . In general, just be aware of these rules.

Bottom line

This article did not cover attribute selectors, but in general I have already written about them before. I wish you success in learning website building, including CSS selectors.

I would also like to add that if you use jQuery, then it has its own selectors, although they are very similar to these, but there are slight differences.

Last update: 04/21/2016

Defining a style starts with a selector. For example:

Div( width:50px; /* width */ height:50px; /* height */ background-color:red; /* background color */ margin: 10px; /* indentation from other elements */ )

In this case, the selector is div . A number of selectors inherit the name of the formatted elements, for example, div, p, h2, etc. When such a selector is defined, its style will be applied to all elements matching this selector. That is, the above defined style will be applied to all elements

on the web page:

CSS selectors

CSS selectors

There are 3 divs on the page, and they will all be styled:

Classes

Sometimes the same elements require different styling. And in this case we can use classes.

To define a class selector in CSS, a dot is placed before the class name:

RedBlock( background-color:red; )

The class name can be arbitrary. For example, in this case the class name is "redBlock". However, it is allowed to use letters, numbers, hyphens and underscores in the class name, and the class name must begin with a letter.

It is also worth considering the case of names: the names "article" and "ARTICLE" will represent different classes.

Once a class is defined, we can apply it to an element using the class attribute. For example:

Let's define and use several classes:

CSS classes

CSS classes

Identifiers

To identify elements unique on a web page, identifiers are used, which are determined using id attributes. For example, a page might have a head block or header:

Defining styles for identifiers is similar to defining classes, only the hash symbol # is used instead of a dot:

CSS IDs

Main content

However, it is worth noting that identifiers have more to do with the structure of the web page and less with styling. Classes are used for styling rather than identifiers.

Universal selector

In addition to tag, class and identifier selectors, css also has the so-called universal selector, which represents the asterisk (*). It applies styles to all elements on the html page:

*( background-color: red; )

Styling a group of selectors

Sometimes certain styles are applied to a range of selectors. For example, let's say we want to apply an underline to all headings. In this case, we can list the selectors of all elements separated by commas:

CSS selectors

CSS3

Selectors

Selector group

Some text...

A selector group can contain both tag selectors and class and identifier selectors, for example:

H1, #header, .redBlock( color: red; )







2024 gtavrl.ru.