MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Esta tradução está incompleta. Por favor, ajude a traduzir este artigo.

Esta é a 5ª seção de Primeiros passos (Tutorial Css), ela explica como você pode aplicar estilos seletivamente e como diferentes tipos de seletores possuem diferentes prioridades. Você adiciona mais atributos para tags no seu documento e como você pode usa-los em sua folha de estilos.

Informações: Seletores

CSS tem sua propria terminologia para descrever a linguagem CSS. Anteriormente nesse tutorial, você criou linha no seu stylesheet como esta:

strong {
  color: red;
}

No CSS, este código inteiro é uma regra. Esta regra inicia com strong, que é um seletor. Ele seleciona os elementos do DOM aos quais a regra se aplica.

Mais detalhes

A parte dentro das chaves é a declaração.

A palavra-chave color é uma propriedade e red é um valor.

O ponto e vírgula depois do par propriedade-valor o separa de outros pares propriedade-valor na mesma declaração.

Esse tutorial se refere ao seletor strong como um seletor de tag. A Especificação do CSS se refere a este seletor como seletor de tipo.

Esta página de tutorial explica mais sobre os seletores que você pode utilizar nas regras CSS.

Em adição aos nomes das tags, você pode usar valores de atributos nos seletores. Isso permite que as regras sejam mais específicas.

Dois atributos são especiais para o CSS. São eles o class e o id.

Seletores com Classe

Use o atributo class em um elemento para atribuir o elemento a uma determinada classe. O nome da classe é de sua escolha. Muitos elementos em um documento podem pertencer a mesma classe.

Em seu CSS, digite um ponto final antes do nome da classe para usar como um seletor.

Seletores com ID

Use o atributo id em um elemento para atribuir um ID a esse elemento. O nome do ID é de sua escolha e ele deve ser único no documento.

Em seu CSS, digite cerquilha (hashtag) antes do ID quanto estiver usando em um seletor.

Exemplo
Esta tag HTML tem tanto um atributo class quanto um atributo id:
<p class="chave" id="principal">

O valor de id, principal, precisa ser unico no documento, mas outras tags no documento podem ter o atributo class com o mesmo nome, chave.

Em uma folha de estilo CSS, esta regra torna verde todos os elementos da classe chave. (Eles podem ou não serem elementos <p>.)

.chave {
  color: green;
}

Esta regra torna negrito um elemento com id principal:

#principal {
  font-weight: bolder;
}

Seletores de Atributo

Você não está restrito aos dois atributos especiais, class e id. Você pode especificar outros atributos usando colchetes. Dentro dos colchetes você insere o nome do atributo, opcionalmente seguido por um operador correspondente e um valor. Além disso, a seleção pode ser feita case-insensitive adicionando um "i" depois do valor, mas nem todos os browsers suportam esta funcionalidade ainda. Exemplos:

[disabled]
Seleciona todos os elementos com o atributo "disabled".
[type='button']
Seleciona todos os elementos do tipo "button".
[class~=key]
Selects elements with the class "key" (but not e.g. "keyed", "monkey", "buckeye"). Functionally equivalent to .key.
[lang|=es]
Selects elements specified as Spanish. This includes "es" and "es-MX" but not "eu-ES" (which is Basque).
[title*="example" i]
Selects elements whose title contains "example", ignoring case. In browsers that don't support the "i" flag, this selector probably won't match any element.
a[href^="https://"]
Selects secure links.
img[src$=".png"]
Indirectly selects PNG images; any images that are PNGs but whose URL doesn't end in ".png" (such as when there's a query string) won't be selected.

Pseudo-classes selectors

A CSS pseudo-class is a keyword added to selectors that specifies a special state of the element to be selected. For example :hover will apply a style when the user hovers over the element specified by the selector.

Pseudo-classes, together with pseudo-elements, let you apply a style to an element not only in relation to the content of the document tree, but also in relation to external factors like the history of the navigator (:visited, for example), the status of its content (like :checked on some form elements), or the position of the mouse (like :hover which lets you know if the mouse is over an element or not). To see a complete list of selectors, visit CSS3 Selectors working spec.

Syntax
selector:pseudo-class {
  property: value;
} 

List of pseudo-classes

Information: Specificity

Multiple rules may have selectors that each match the same element. If a property is given in only one rule, there is no conflict and the property is set on the element. If more than one rule applies to an element and sets the same property, then CSS gives priority to the rule that has the more specific selector. An ID selector is more specific than a class, pseudo-class or attribute selector, which in turn are more specific than a tag or pseudo-element selector.

More details

You can also combine selectors, making a more specific selector. For example, the selector .key selects all elements that have the class name key. The selector p.key selects only <p> elements that have the class name key.

If the stylesheet has conflicting rules and they are equally specific, then CSS gives priority to the rule that is later in the stylesheet.

When you have a problem with conflicting rules, try to resolve it by making one of the rules more specific, so that it has priority. If you cannot do that, try moving one of the rules nearer the end of the stylesheet so that it has priority.

Information: Selectors based on relationships

CSS has some ways to select elements based on the relationships between elements. You can use these to make selectors that are more specific.

Common selectors based on relationships
Selector Selects
A E Any E element that is a descendant of an A element (that is: a child, or a child of a child, etc.)
A > E Any E element that is a child (i.e. direct descendant) of an A element
E:first-child Any E element that is the first child of its parent
B + E Any E element that is the next sibling of a B element (that is: the next child of the same parent)

You can combine these to express complex relationships.

You can also use the symbol * (asterisk) to mean "any element".

Example

An HTML table has an id attribute, but its rows and cells do not have individual identifiers:

<table id="data-table-1">
...
<tr>
<td>Prefix</td>
<td>0001</td>
<td>default</td>
</tr>
...

These rules make the first cell in each row underline, and the sibling of first cell in each row strikethroughted (in example 2.nd cell) . They only affect one specific table in the document:

    #data-table-1 td:first-child {text-decoration: underline;}
    #data-table-1 td:first-child + td {text-decoration: line-through;}

The result looks like:

Prefix 0001 default
More details

In the usual way, if you make a selector more specific, then you increase its priority.

If you use these techniques, you avoid the need to specify class or id attributes on so many tags in your document. Instead, CSS does the work.

In large designs where speed is important, you can make your stylesheets more efficient by avoiding complex rules that depend on relationships between elements.

For more examples about tables, see Tables in the CSS Reference page.

Action: Using class and ID selectors

  1. Edit your HTML file, and duplicate the paragraph by copying and pasting it.
  2. Then add id and class attributes to the first copy, and an id attribute to the second copy as shown below. Alternatively, copy and paste the entire file again:
    <!doctype html>
    <html>
      <head>
      <meta charset="UTF-8">
      <title>Sample document</title>
      <link rel="stylesheet" href="style1.css">
      </head>
      <body>
        <p id="first">
          <strong class="carrot">C</strong>ascading
          <strong class="spinach">S</strong>tyle
          <strong class="spinach">S</strong>heets
        </p>
        <p id="second">
          <strong>C</strong>ascading
          <strong>S</strong>tyle
          <strong>S</strong>heets
        </p>
      </body>
    </html>
    
  3. Now edit your CSS file. Replace the entire contents with:
    strong { color: red; }
    .carrot { color: orange; }
    .spinach { color: green; }
    #first { font-style: italic; }
    
  4. Save the files and refresh your browser to see the result:
    Cascading Style Sheets
    Cascading Style Sheets

    You can try rearranging the lines in your CSS file to show that the order has no effect.

    The class selectors .carrot and .spinach have priority over the tag selector strong.

    The ID selector #first has priority over the class and tag selectors.

Challenges
  1. Without changing your HTML file, add a single rule to your CSS file that keeps all the initial letters that same color as they are now, but makes all the other text in the second paragraph blue:
    Cascading Style Sheets
    Cascading Style Sheets
  2. Now change the rule you have just added (without changing anything else), to make the first paragraph blue too:
    Cascading Style Sheets
    Cascading Style Sheets
Possible solution
  1. Add a rule with an ID selector of #second and a declaration color: blue;, as shown below:
    #second { color: blue; }
    
    A more specific selector, p#second also works.
  2. Change the selector of the new rule to be a tag selector using p:
    p { color: blue; }
    
Hide solution
See a solution for the challenge.

Action: Using pseudo-classes selectors

  1. Create an HTML file with following content:
    <!doctype html>
    <html>
      <head>
      <meta charset="UTF-8">
      <title>Sample document</title>
      <link rel="stylesheet" href="style1.css">
      </head>
      <body>
        <p>Go to our <a class="homepage" href="http://www.example.com/" title="Home page">Home page</a>.</p>
      </body>
    </html>
    
  2. Now edit your CSS file. Replace the entire contents with:
    a.homepage:link, a.homepage:visited {
      padding: 1px 10px 1px 10px;
      color: #fff;
      background: #555;
      border-radius: 3px;
      border: 1px outset rgba(50,50,50,.5);
      font-family: georgia, serif;
      font-size: 14px;
      font-style: italic;
      text-decoration: none;
    }
    
    a.homepage:hover, a.homepage:focus, a.homepage:active {
      background-color: #666;
    }
    
  3. Save the files and refresh your browser to see the result (put the mouse over the following link to see the effect):
    Go to our Home page  

Action: Using selectors based on relationships and pseudo-classes

With selectors based on relationships and pseudo-classes you can create complex cascade algorithms. This is a common technique used, for example, in order to create pure-CSS dropdown menus (that is only CSS, without using JavaScript). The essence of this technique is the creation of a rule like the following:

div.menu-bar ul ul {
  display: none;
}

div.menu-bar li:hover > ul {
  display: block;
}

to be applied to an HTML structure like the following:

<div class="menu-bar">
  <ul>
    <li>
      <a href="example.html">Menu</a>
      <ul>
        <li>
          <a href="example.html">Link</a>
        </li>
        <li>
          <a class="menu-nav" href="example.html">Submenu</a>
          <ul>
            <li>
              <a class="menu-nav" href="example.html">Submenu</a>
              <ul>
                <li><a href="example.html">Link</a></li>
                <li><a href="example.html">Link</a></li>
                <li><a href="example.html">Link</a></li>
                <li><a href="example.html">Link</a></li>
              </ul>
            </li>
            <li><a href="example.html">Link</a></li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

See our complete CSS-based dropdown menu example for a possible cue.

What next?

Your sample stylesheet is starting to look dense and complicated. The next section describes ways to make CSS easier to read.

Etiquetas do documento e colaboradores

 Colaboradores desta página: RafaelRNunes, Gregory, macarena, agathasilva28
 Última atualização por: RafaelRNunes,