Sie sind auf Seite 1von 11

Selector

Example

Example description

CSS

.class

.intro

Selects all elements with class="intro"

#id

#firstname

Selects the element with id="firstname"

Selects all elements

element

Selects all <p> elements

element,element

div,p

Selects all <div> elements and all <p> elements

element element

div p

Selects all <p> elements inside <div> elements

element>element

div>p

Selects all <p> elements where the parent is a <div>


element

element+element

div+p

Selects all <p> elements that are placed immediately


after <div> elements

[attribute]

[target]

Selects all elements with a target attribute

[attribute=value]

[target=_blank]

Selects all elements with target="_blank"

[attribute~=value]

[title~=flower]

Selects all elements with a title attribute containing


the word "flower"

[attribute|=value]

[lang|=en]

Selects all elements with a lang attribute value starting 2


with "en"

:link

a:link

Selects all unvisited links

:visited

a:visited

Selects all visited links

:active

a:active

Selects the active link

:hover

a:hover

Selects links on mouse over

:focus

input:focus

Selects the input element which has focus

:first-letter

p:first-letter

Selects the first letter of every <p> element

:first-line

p:first-line

Selects the first line of every <p> element

:first-child

p:first-child

Selects every <p> element that is the first child of its


parent

:before

p:before

Insert content before the content of every <p>


element

:after

p:after

Insert content after every <p> element

:lang(language)

p:lang(it)

Selects every <p> element with a lang attribute value 2


starting with "it"

element1~element2 p~ul

Selects every <ul> element that are preceded by a


<p> element

[attribute^=value]

a[src^="https"]

Selects every <a> element whose src attribute value


begins with "https"

[attribute$=value]

a[src$=".pdf"]

Selects every <a> element whose src attribute value


ends with ".pdf"

[attribute*=value]

a[src*="w3schools"] Selects every <a> element whose src attribute value


contains the substring "w3schools"

:first-of-type

p:first-of-type

Selects every <p> element that is the first <p>


element of its parent

:last-of-type

p:last-of-type

Selects every <p> element that is the last <p>


element of its parent

:only-of-type

p:only-of-type

Selects every <p> element that is the only <p>


element of its parent

:only-child

p:only-child

Selects every <p> element that is the only child of its


parent

:nth-child(n)

p:nth-child(2)

Selects every <p> element that is the second child of

its parent
:nth-last-child(n)

p:nth-last-child(2)

Selects every <p> element that is the second child of


its parent, counting from the last child

:nth-of-type(n)

p:nth-of-type(2)

Selects every <p> element that is the second <p>


element of its parent

:nth-last-of-type(n) p:nth-last-oftype(2)

Selects every <p> element that is the second <p>


element of its parent, counting from the last child

:last-child

p:last-child

Selects every <p> element that is the last child of its


parent

:root

:root

Selects the documents root element

:empty

p:empty

Selects every <p> element that has no children


(including text nodes)

:target

#news:target

Selects the current active #news element (clicked on a 3


URL containing that anchor name)

:enabled

input:enabled

Selects every enabled <input> element

:disabled

input:disabled

Selects every disabled <input> element

:checked

input:checked

Selects every checked <input> element

:not(selector)

:not(p)

Selects every element that is not a <p> element

::selection

::selection

Selects the portion of an element that is selected by a


user

Selector

A qu tags afecta
Cmo est situado el tag respecto a otros tags

*
tag

Cualquier tag html.


un tag especfico.
Por ejemplo, div equivaldra al tag <div>

tag1 tag2

un tag2 anidado dentro de un tag1, en cualquier nivel de


anidamiento.
Por ejemplo, vale
<tag1>...<otro>...<tag2>...</tag2>...</otro>...</tag1>
Es decir, un tag2 que sea hijo, nieto, bisnieto... de tag1

tag1 > tag2

Un tag2 que sea hijo de tag1. No valen nietos.

tag1 + tag2

Un tag2 que va detrs y es adyacente a tag1.

tag:first-child

tag que sea el primer hijo de su padre.


Con algn evento de usuario

tag:link
tag :visited

Para un tag que hace de hiperenlace. El ms tpico es <a>, aunque


puede ser una <img>, etc. Afecta segn no se haya visitado todava
(link) o s se haya visitado (visited)

tag:active
tag :hover
tag :focus

Un tag mientras se est haciendo click en l (active), cuando est el


ratn sobre l (hover) o cuando tiene el foco (focus)
tags con atributos

tag[atributo]

Un tag que tenga el atributo, con cualquier valor

tag[atributo="valor"] Un tag con el atributo asignado al valor.


tag[atributo~="valor"]

Un tag con un atributo cuyo valor son varios valores separados por
comas y uno de ellos es valor.

tag.clase

Un tag con atributo class igual a clase. Es una forma abreviada que
permite css de poner tag[class="~valor"]

tag#id

Un tag con atributo id igual a id. Es una forma abreviada que permite
css de poner tag[id="~id"]

Podemos especificar varios elementos separados por comas y el estilo se aplicara a todos ellos
por igual.
a, p {
font-size: 12px;
}
--------------------------Se utilizan para separar palabras clave. Tambin pueden utilizarse para anidar selectores
si son colocados entre estos. Al anidar selectores, el estilo se aplicar al ltimo elemento
mencionado, pero debe cumplirse la condicin de que ste debe estar dentro de los elementos
anteriores. Un ejemplo para aclarar dudas:
div a {
color: orange;
}
Todas las etiquetas a que estn dentro de una etiqueta div tendrn orange (naranja)
--------------------------div#mi_ejemplo {
/* ... */
}
Ese cdigo modificara el estilo de cualquier etiqueta div con id mi_ejemplo. Si le quitamos el
nombre de la etiqueta, el estilo se aplicara a cualquier etiqueta con id mi_ejemplo.
--------------------------Otra caracterstica es que una etiqueta puede tener varias clases a la vez, separadas por
espacios.
Por ejemplo:
<a class=letraGrande subrayado>

La etiqueta a recibir el estilo de las clases letraGrande y subrayado, ya que pertenece a


ambas. El cdigo CSS de dichas clases podra ser parecido a este:
.letraGrande {
font-size: 20px;}
.subrayado {
/* As se subraya un texto */
text-decoration: underline;
}
--------------------------Si queremos referirnos a un elemento que posee varios atributos a la vez, deberemos
escribirlos en el orden en que fueron nombrados, es decir, primero la ID, luego la clase, y luego
la pseudo-clase. Ah va un cdigo de ejemplo:
img#logo.sinMargen:hover {
border: 1px solid #000;
}
Solamente podemos especificar un atributo de cada tipo, lo que se traduce a que lo mximo
que podemos utilizar es una ID, una clase y una pseudo-clase, ni un solo atributo ms.
--------------------------El selector universal se marca con un asterisco * y abarca a todos los elementos del
documento HTML. El siguiente ejemplo aplicara un fondo amarillo a todos los elementos que
soportasen la propiedad background-color salvo que se usase un selector ms especfico que
lo sobrescriba.
* { background-color: yellow; }
--------------------------El atributo class se indica con un punto y se aplica a todos los elementos del documento con
esa clase. El siguiente ejemplo aplicar un fondo amarillo a todos los elementos <li> marcados
por la clase entrega (<li class="entrega">)
li.entrega { background-color: yellow; }
--------------------------El atributo id debe ser nico dentro del documento web, por tanto slo puede aplicarse a una
nica aparicin de un elemento dentro del rbol del documento. El selector CSS para indicar
los id es la almohadilla #. El siguiente ejemplo aplicar un fondo amarillo al elemento <h2>
que tenga el id nico ofertas (<h2 id="ofertas">)
h2#ofertas { background-color: yellow; }

Dado que el selector id debe ser nico, es totalmente seguro utilizar el selector univers al
(*#idNombre o #idNombre). Para mejorar la legibilidad y la facilidad en el mantenimiento
suele ser buena idea conservar el nombre del elemento en su lugar (h2#idNombre).
--------------------------Son llamados pseudo-elementos porque en realidad no existen en el documento fuente
(ninguna marca identifica la primer letra de un prrafo, por ejemplo) pero son muy tiles para
seleccionar elementos importantes dentro de la composicin.
CSS 2.1 tiene cuatro pseudo elementos:
:first-line Permite aplicar un estilo determinado a la primera lnea de un prrafo.
:first-letter Permite seleccionar la primer letra de un prrafo, generalmente para utilizarla
como capitular (en un tamao mayor que el resto del prrafo)
:before Permite insertar un contenido antes de un elemento determinado y definir el estilo del
contenido insertado
:after Permite insertar un contenido despus de un elemento determinado y definir el estilo
del contenido insertado
p:first-line { text-transform: uppercase; }
p:first-letter { font-size: 2em; }
h3:before { content: "Tema: "; }
p:after { content: url("icono.gif"); }
body:after {
content: "Fin";
display: block;
}
--------------------------<html>
<head>
<title>Prueba Clases</title>
<style type="text/css">
div.header{
width: 780px;
height: 256px;
border: dotted 1px #999999;
position: relative;
}
div.header div.logo{
float: left;
width: 256px;
height: 256px;
}
div.header div.links{
float: right;

position: relative;
padding-top: 10px;
}
div.header div.links div{
margin-right: 17px;
background-repeat: no-repeat;
background-position: 0 2px;
padding-left: 21px;
}
div.header div.links div.inicio{
float: left;
background-image: url(inicio.png);
background: blue;
}
div.header div.links div.mapa{
float: left;
background-image: url(sitemap.png);
background: green;
}
div.header div.links div.contacto{
float: left;
background-image: url(email.png);
background: red;
}
</style>
</head>
<body>
<div class="header">
<div class="logo"><img src="splash.png" alt="Mi logo" width="256" height="256"
/></div>
<div class="links">
<div class="inicio">Inicio</div>
<div class="mapa">Mapa del Sitio</div>
<div class="contacto">Contctame</div>
</div>
</div>
</body>
</html>
--------------------------You can combine various class selectors together as shown below:
#content, #footer, #supplement {
position: absolute;
left: 510px;
width: 200px;

}
--------------------------Pseudo-classes can be combined with CSS classes:
a.red:visited {color:#FF0000;}
<a class="red" href="css_syntax.asp">CSS Syntax</a>
--------------------------For example, if we have the following CSS declaration,
b.special {
color:#0000FF;
}
i.special {
color:#FF0000;
}
--------------------------.applylarge {
font-size:20px;
}
.applyred {
color:#FF0000;
}
<p class="applylarge applyred">This is an example of multiple classes.</p>
--------------------------h2 {
color: red;
}
.thisOtherClass {
color: red;
}
.yetAnotherClass {
color: red;

}
You could make it:
h2, .thisOtherClass, .yetAnotherClass {
color: red;
}
--------------------------#top {
background-color: #ccc;
padding: 1em
}
#top h1 {
color: #ff0;
}
#top p {
color: red;
font-weight: bold;
}
Removes the need for classes or ID's if it is applied to HTML that looks something like this:
<div id="top">
<h1>Chocolate curry</h1>
<p>This is my recipe for making curry purely with chocolate</p>
<p>Mmm mm mmmmm</p>
</div>
--------------------------td{
font-family: verdana, arial !important;
}
td.micelda{
font-family: monospace;
}

Que aplicado sobre el siguiente HTML:


<table>
<tr>
<td class="micelda">Hola</td>
<td>23232</td>
</tr>
</table>
--------------------------Se puede seleccionar una etiqueta dentro de un contexto dado, es decir, segn los elementos
que se encuentran alrededor, mediante selectores contextuales.
Existen varios tipos de selectores contextuales:
El selector anidado se usa para crear una regla que se aplica solamente cuando el elemento Y
est anidado dentro del elemento X. Su sintaxis es:
selector_X selector_Y { /* style; */ }
Para el siguiente cdigo HTML:
<p> <i>Nota</i>, esto es una <b>advertencia</b> </p>
<b> Leer detenidamente </b>
La siguiente regla slo afecta a la palabra "advertencia" (la nica rodeada por etiquetas <B>
que estn a su vez anidadas dentro de un grupo de etiquetas <P>):
P B { font-weight: bold; color: red; }
El selector de hermanos adyacentes se usa para crear una regla que se aplica solamente
cuando el elemento Y le sigue inmediatamente al elemento X. Su sintaxis es:
selector_X + selector_Y { /* style; */ }
Para el siguiente cdigo HTML:
<p> <i>Nota</i>, esto es una <b>advertencia</b> </p>
<b> Leer detenidamente </b>
La siguiente regla slo afecta a la palabra "advertencia" (la nica rodeada por etiquetas <B>
que a su vez siguen al grupo de etiquetas <l>):
I + B { font-weight: bold; color: red; }
El selector de hijo se usa para crear una regla que solamente se aplica cuando el elemento Y es
descendiente del elemento X. La regla no se aplica si Y se encuentra dentro de una o ms
etiquetas intermediarias. Su sintaxis es:
selector_X > selector_Y { /* style; */ }
Para el siguiente cdigo HTML:
<p> <b><i> Nota </i></b>, esto es una <i><b> advertencia </b></i> </p>
<b> Leer detenidamente </b>
La siguiente regla slo afecta al elemento "<i> Nota </i>" (la nica rodeada por etiquetas <B>
que estn a su vez dentro de un grupo de etiquetas <P>):

P > B { font-weight: bold; color: red; }


--------------------------Vamos a ver algunos ejemplos.
/* Pone color rojo a TODOS los tags de html de la pgina */
*{
color:red;
}
/* Todos los tags con class="importante" salen en rojo */
*.importante {
color:red;
}
/* En estos casos que * va delante, CSS admite que lo omitamos. Tiene el mismo efecto poner
esto otro */
.importante {
color:red;
}
/* Pone de color rojo TODOS los prrafos */
p{
color:red;
}
/* Pone de color rojo todos los parrafos que estn dentro de un div, en cualquier nivel de
anidamiento */
div p {
color:red;
}
...
<div>esto es un div
<p>con un parrafo dentro</p>
</div>
<p>y este esta fuera</p>
/* Pone de color los rojo los span que sean hijos de div */
div > span {
color:red;
}
<div>un div con <span>span hijo</span></div>
<div><p>un div con <span>span nieto</span></p></div>

/* Pone de color rojo los parrafos que van detras de un div */


div + p {
color:red;
}
<div>texto 1</div><p>parrafo 1</p><p>parrafo 2</p>
Del resto slo un ejemplo, son todos muy parecidos.
/* Pone de color rojo los parrafos que tengan align center */
p[align="center"] {
color:red;
}
<p align="center>centrado y rojo</p><p>normal</p>
---------------------------

Das könnte Ihnen auch gefallen