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

::before (:before)

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

Sumário

::before cria um pseudo-elemento que é o primeiro filho do elemento atingido. É frequentemente utilizado para adicionar conteúdo decorativo à um element utilizando a propriedade content. Este elemento é inline por padrão.

Sintaxe

/* CSS3 syntax */
::before { style properties }

/* CSS2 syntax */
:before { style properties }

A notação ::before (com dois colons) foi introduzida no CSS3 afim de diferenciar pseudo-classes de pseudo-elementos. Navegadores também aceitam a notação :before introduzida no CSS 2.

Exemplos

Adicionando aspas

Um exemplo simples do uso de pseudo-elementos ::before pseudo-elements é a exibição de aspas. Aqui usamos ::before e ::after para inserir caracteres de aspas.

Conteúdo HTML

<q>Some quotes</q>, he said, <q>are better than none</q>.

Conteúdo CSS

q::before { 
  content: "«";
  color: blue;
}
q::after { 
  content: "»";
  color: red;
}

Saída

Exemplo decorativo

Podemos estilizar textos e imagens na propriedade content praticamente da forma que desejarmos.

Conteúdo HTML

<span class="ribbon">Notice where the orange box is.</span>

Conteúdo CSS

.ribbon {
  background-color: #5BC8F7;
}

.ribbon::before {
  content: "Look at this orange box.";
  background-color: #FFBA10;
  border-color: black;
  border-style: dotted;
}

Saída

Lista To-do

Neste exemplo vamos criar uma simples lista to-do, usando pseudo-elementos. Este método pode frequentemente ser utilizado para dar pequenos toques touches à UI (User Interface) e melhorar a experiência do usuário.

Conteúdo HTML

<ul>
  <li>Buy milk</li>
  <li>Take the dog for a walk</li>
  <li>Exercise</li>
  <li>Write code</li>
  <li>Play music</li>
  <li>Relax</li>
</ul>

Conteúdo CSS

li {
  list-style-type: none;
  position: relative;
  margin: 2px;
  padding: 0.5em 0.5em 0.5em 2em;
  background: lightgrey;
  font-family: sans-serif;
}

li.done {
  background: #CCFF99;
}

li.done::before {
  content: '';
  position: absolute;
  border-color: #009933;
  border-style: solid;
  border-width: 0 0.3em 0.25em 0;
  height: 1em;
  top: 1.3em;
  left: 0.6em;
  margin-top: -1em;
  transform: rotate(45deg);
  width: 0.5em;
}

Conteúdo JavaScript

var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if( ev.target.tagName === 'LI') {
     ev.target.classList.toggle('done'); 
  }
}, false);

Aqui está rodando o código acima. Perceba que nenhum ícone é utilizado e o check-mark é o ::before que foi estilizado no CSS.

Saída

Notas

Although the positioning fixes in Firefox 3.5 do not allow content to be generated as a separate previous sibling (as per the CSS spec stating "The :before and :after pseudo-elements elements interact with other boxes... as if they were real elements inserted just inside their associated element."), they can be used to provide a slight improvement on tableless layouts (e.g., to achieve centering) in that, as long as the content to be centered is wrapped in a further child, a column before and after the content can be introduced without adding a previous or following sibling (i.e., it is perhaps more semantically correct to add an additional span as below, than it would to add an empty <div/> before and after). (And always remember to add a width to a float, since, otherwise, it will not float!)

HTML content

<div class="example">
<span id="floatme">"Floated Before" should be generated on the left of the 
viewport and not allow overflow in this line to flow under it. Likewise 
should "Floated After" appear on the right of the viewport and not allow this 
line to flow under it.</span>
</div>

CSS content

#floatme { float: left; width: 50%; }

/* To get an empty column, just indicate a hex code for a non-breaking space: \a0 as the content (use \0000a0 when following such a space with other characters) */
.example::before {
  content: "Floated Before";
  float: left;
  width: 25%
}
.example::after {
  content: "Floated After";
  float: right;
  width:25%
}

/* For styling */
.example::before, .example::after, .first {
  background: yellow;
  color: red;
}

Output

Specifications

Specification Status Comment
CSS Pseudo-Elements Level 4
The definition of '::before' in that specification.
Working Draft No significant changes to the previous specification.
CSS Transitions Working Draft Allows transitions on properties defined on pseudo-elements.
CSS Animations Working Draft Allows animations on properties defined on pseudo-elements.
Selectors Level 3
The definition of '::before' in that specification.
Recommendation Introduces the two-colon syntax.
CSS Level 2 (Revision 1)
The definition of '::before' in that specification.
Recommendation Initial definition, using the one-colon syntax

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
:before support (Yes) 1.0 (1.7 or earlier)[1] 8.0 4 4.0
::before support (Yes) 1.5 (1.8)[1] 9.0 7 4.0
Support of animations and transitions 26 4.0 (2.0) Não suportado Não suportado Não suportado
Feature Android Chrome Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
:before support (Yes) (Yes) (Yes) ? ? ?
::before support (Yes) (Yes) (Yes) 7.1 ? 5.1
Support of animations and transitions 26 (Yes) 4.0 (4.0) Não suportado Não suportado Não suportado

[1] Firefox prior to version 3.5 only implemented the CSS 2.0 version of :before. Not allowed were position, float, list-style-* and some display properties. Firefox 3.5 removed those restrictions.

See also

Etiquetas do documento e colaboradores

 Colaboradores desta página: marcioleandro
 Última atualização por: marcioleandro,