W3docs

Estilos HTML - CSS

Aprende a añadir CSS a elementos HTML de 3 formas, aplica estilos con distintas propiedades CSS y consulta ejemplos prácticos.

CSS se utiliza para dar estilo a HTML. Determina cómo aparecen los elementos HTML en pantalla, en papel u otros medios.

CSS ahorra mucho trabajo. Puede controlar el diseño de varias páginas a la vez.

Puedes añadir CSS a elementos HTML de 3 maneras:

  • En línea (Inline) — el atributo style se añade directamente al elemento HTML.
  • Interno (Internal) — un elemento <style> se coloca en la sección <head> de la página.
  • Externo (External) — un archivo .css independiente se vincula a la página.

¿Por qué tres métodos? Cada uno sacrifica comodidad a cambio de alcance. Los estilos en línea son rápidos, pero solo se aplican a un único elemento. Los estilos internos cubren una sola página. Las hojas de estilo externas son el enfoque recomendado para proyectos reales, ya que un solo archivo puede dar estilo a todo un sitio web y el navegador lo almacena en caché.

Prioridad en cascada

Cuando más de una regla apunta al mismo elemento, CSS resuelve el conflicto mediante la especificidad y el orden de origen. Como regla general, cuanto más cerca se declara un estilo del elemento, mayor es su prioridad:

style en línea > <style> interno > hoja de estilo externa

Así, si una hoja externa indica que un párrafo es azul y un style en línea dice que es rojo, el párrafo será rojo. (La bandera !important puede anular este orden, pero úsala con moderación.) Obtén más información en la introducción a CSS.

Veamos cada método en detalle.

CSS en línea

Un CSS en línea aplica un estilo concreto a un único elemento HTML. Para ello se utiliza el atributo style del elemento HTML.

En el siguiente ejemplo, el color del texto del elemento <p> es rojo:

Ejemplo de CSS en línea:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <h1>Usage of the inline CSS</h1>
    <p style="color:red;">The paragraph is red.</p>
  </body>
</html>

CSS interno

Un CSS interno especifica el estilo para una única página HTML. Se define en el elemento <head> de la página HTML, dentro de una etiqueta <style>:

Ejemplo de CSS interno:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      body {
        background-color: yellow;
      }
      h1 {
        font-size: 30px;
      }
      p {
        font-size: 18px;
      }
    </style>
  </head>
  <body>
    <h1>Lorem Ipsum</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

CSS externo

Una hoja de estilo externa especifica el estilo para múltiples páginas HTML. Puede cambiar el aspecto de todo un sitio web modificando un solo archivo.

Para usar una hoja de estilo externa, añade un <link> dentro del elemento <head> de la página HTML. El atributo href apunta a la ruta del archivo .css:

Ejemplo de hoja de estilo CSS externa:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <h1>Lorem Ipsum</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

El archivo styles.css vinculado contiene las reglas. No puede incluir código HTML y debe guardarse con la extensión .css. Para la página anterior, styles.css podría tener este aspecto:

body {
  background-color: yellow;
}
h1 {
  font-size: 30px;
}
p {
  font-size: 18px;
}

Fuentes y colores en CSS

La propiedad CSS font-family define la tipografía del contenido de texto.

La propiedad CSS font-size define el tamaño del texto.

La propiedad CSS color establece el color del propio texto. (Ten en cuenta que color no es una propiedad de fuente — controla el color del texto en primer plano.)

La propiedad CSS background-color establece el color detrás del elemento.

Ejemplo de fuentes y colores en CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      h1 {
        color: #008000;
        font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
        font-size: 200%;
      }
      p {
        color: #666666;
        font-family: 'New Roman', serif;
        font-size: 150%;
      }
    </style>
  </head>
  <body>
    <h1>Lorem Ipsum</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Borde CSS

La propiedad CSS border establece valores para los cuatro lados de un elemento.

Ejemplo de la propiedad border de CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        border: 2px dotted red;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Relleno CSS (Padding)

La propiedad CSS padding especifica el relleno (espacio) entre el texto y el borde.

Ejemplo de la propiedad padding de CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        border: 2px dashed #008022;
        padding: 50px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Margen CSS (Margin)

La propiedad CSS margin crea espacio alrededor del elemento.

Ejemplo de la propiedad margin de CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      p {
        border: 2px dashed #090fce;
        margin: 50px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

El atributo id

El atributo id apunta a un único elemento único. Un valor de id debe ser único dentro de la página — no puede haber dos elementos con el mismo id. En CSS se selecciona con una almohadilla, por ejemplo #large-text.

Ejemplo del atributo id:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      #large-text {
        border: 8px groove powderblue;
        font-size: 24px;
        padding: 20px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p id="large-text">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

El atributo class

El atributo class es reutilizable: la misma clase puede aplicarse a cualquier número de elementos, y un solo elemento puede llevar varias clases. Esto convierte a las clases en la herramienta adecuada para dar el mismo estilo a un grupo de elementos. En CSS se selecciona una clase con un punto, por ejemplo .text.

Ejemplo del atributo class:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .text {
        border: 8px inset powderblue;
        font-size: 20px;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <h1>Heading</h1>
    <p class="text">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p>
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
    <p class="text">
      Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book.
    </p>
  </body>
</html>

Práctica

Práctica
¿Cuáles son las formas de añadir estilos CSS a un documento HTML según el artículo de w3docs?
¿Cuáles son las formas de añadir estilos CSS a un documento HTML según el artículo de w3docs?
Práctica
Si una hoja de estilo externa establece un párrafo en azul y un atributo style en línea lo establece en rojo, ¿qué color prevalece?
Si una hoja de estilo externa establece un párrafo en azul y un atributo style en línea lo establece en rojo, ¿qué color prevalece?
Was this page helpful?