History: CSS - Lenguaje de estilos

Revision made 7 years ago by Francisco Presencia. Go to the last revision.

En esta lección aprenderás a darle forma, color y orden al contenido que hemos escrito previamente usando CSS. También aprenderás los conceptos básicos de diseño y estructura de páginas web.

Como habéis visto en el html, ya hemos in­cluido Pic­nic CSS en la web para par­tir de una base sobre la que con­struir el resto del es­tilo. Hay muc­has li­brerías parecidas, in­cluyen­do la famosa pero com­pleja Bootstrap.

El CSS siempre modifica al HTML, no puede ex­is­tir de forma in­depen­dien­te al mismo.

Selec­tores y pro­piedades

Para saber a qué elemen­to modifica, se utiliza lo que se llama un selec­tor, y cada una de las de­finiciones de es­tilos que se hacen se llama una pro­piedad. Por ejemplo, para darle marg­en a todos los pár­rafos:

p {
  margin: 5px;
}

El selec­tor es la p que se en­cuentra en la primera línea. Lo que hace es selec­cionar todos los elemen­tos de tipo párrafo del html.

Después del selec­tor en­contramos las llaves {} que rodean todas las pro­piedades que queramos de­finir para los elemen­tos selec­cionados.

Las pro­piedades son parejas de nombre: valor; , que en este caso sólo es margin: 5px;. Aquí lo que es­tamos in­dican­do es que todos los pár­rafos de la web tien­en un marg­en de 5px.

También se pued­en añadir varias pro­piedades para un mismo selec­tor, por ejemplo cam­bian­do el color de fondo:

p {
  margin: 5px;
  background: rgb(200, 100, 100);
}

Clases

Hay varios tipos de selec­tores. Como re­cor­daréis de la lección an­terior, las clases in­dicamos que tenían un sig­nificado es­peci­al. Por ejemplo, para este HTML:

<section class="flex three">
  <div class="hello">Hello</div>
  <div class="hello world">Hello world</div>
  <div class="bye">Bye</div>
</section>

Vamos a darle es­tilo con CSS (Cas­cade Style Sheet). Para dar­les es­tilos a las clases usaremos el nombre de una de las clases del HTML pre­cedido por un punto .:

/* Estilo para todos los <div> */
div {
  background: red;
}

/* Estilo para todos los elementos con la clase "hello" */
.hello {
  background: green;
}

/* Estilo para todos los elementos con las clases "hello" y "world" */
.hello.world {
  background: blue;
}

Con esto obtendremos lo siguiente:

Re­sum­en: podemos selec­cionar un elemen­to tipo <p> ... </p> con el selec­tor p, sin em­bar­go para selec­cionar un elemen­to con una clase como <a class="important"> ... </a> tendrás que usar el nombre de la clase pre­cedido por un punto como en .important.

Ejer­cicio: para el siguien­te bloque de HTML, haz que todos los links <a> ... </a> parez­can botones. Pista: usa Goog­le para bus­car "CSS But­ton":

<p>Should you <a href="#clickme">click it</a>? asked Alice, incredulous.</p>
<p>At least push the <a href="#redbutton">red button</a>! Se demanded.</p>

Ejer­cicio (avan­zado): para el siguien­te HTML, darle algún es­tilo sólo a los pár­rafos con la clase "quote":

<p>This is a plain paragraph</p>
<p class="quote">This is a styled quote</p>
<a class="quote">this should have no style (;</a>
<div>Good luck!</div>

Layouts

Las págnas web se suel­en diseñar de las estruc­turas más generales (Layouts) a los de­tal­les específicos. Algo básico que tenéis que saber hacer es crear y pro­bar varios layouts de forma rápida. Un ejemplo de Layout:

Cuan­do lo queremos hacer en HTML+CSS, primero tenemos que tener en cuen­ta las par­tes más generales, por lo que re­sul­ta mucho más sen­cil­lo:

Veamos cómo hacer este sen­cil­lo layout. Ya que es genérico, usaremos el elemen­to <div> y clases para hacer la estruc­tura al no disponer de un mejor tipo de elemento en HTML. Primero la línea que lo rodea todo:

<div class="gallery">

  <!-- todo lo demás viene aquí -->

</div>

Como vemos, le as­ig­namos la clase gal­le­ry para el con­tenedor. El nombre de la clase es importante ya que la usaremos más tarde para darle estilo en CSS. Cada uno de los componentes internos tendrá la clase element:

<div class="gallery">
  <div class="element">A</div>
  <div class="element">B</div>
  <div class="element">C</div>
</div>

Ahora nuestros elementos no tienen estilo ni contenido. Vamos a usar el sistema de grids de Picnic CSS para hacernos la vida más fácil. También tendremos que añadir algunos <div> extra (por limitaciones de CSS):

<div class="gallery">
  <div class="flex three">
    <div>
      <div class="element">A</div>
    </div>
    <div>
      <div class="element">B</div>
    </div>
    <div>
      <div class="element">C</div>
    </div>
  </div>
</div>

Si ponemos el código en jsfiddle podemos ver las letras separadas. Para verlo más claramente vamos a darle un estilo básico a los elementos:

.element {
  background: #eee;
  padding: 10px 15px;
  height: 120px;
}

Ahora sí, míralo en este jsfiddle. Se parece mucho más a nuestro objetivo:

Pero la galería empieza desde (0, 0), así que vamos a darle un pequeño margen para que respire con css usando la clase gallery. Acuérdate que a las clases en CSS se les añade un punto:

.gallery {
  margin: 10px;
}

Obtenemos una separación con el cuadrante entero como ves en este jsfiddle:

Box Model

There are three dif­ferent th­ings that can go around your ele­ment and they chan­ge the size of it. Let's see their re­presen­ta­tion first:

The mar­gin is the outer-most space, and it main­ly spaces the dis­tan­ce from one ele­ment to the next one. For ex­am­ple, these but­tons are separated with mar­gins:

Then there is the bord­er. This is a visu­al ele­ment that sur­rounds your ele­ment. For ex­am­ple, input boxes <input> use this nor­mal­ly and here you can see many:

Fin­al­ly, the padd­ing re­presents the space from the bord­er to the con­tent it­self. If the background of the ele­ment is set, the padd­ing will be fil­led with color but the mar­gin will not. Ex­am­ple of dif­ferent padd­ings:

Note that line-height also af­fects the height, that's why we see that even that no-padding seems to have a bit of vert­ical padd­ing (but it's not padd­ing).

Next, we will focus on build­ing the ele­ments. For this, we will also be using HTML, but we will focus on the first one and then we'll con­tinue with to the rest.

So what is in­side our ele­ment? It seems that we want one image and two but­tons. So let's do it:

<div class="element">
  <img src="http://placekitten.com/320/240">
  <button>Like</button>
  <button>Dislike</button>
</div>

But we have a pro­blem, now we have two but­tons but no way of giv­ing style to only one and not the other. To solve this, we will add them dif­ferent clas­ses:

<div class="element">
  <img src="http://placekitten.com/320/240">
  <button class="like">Like</button>
  <button class="dislike">Dislike</button>
</div>

And here you go:

Oops. Not so quick. What is the matt­er? Well, there are two is­sues so far:

  • The image loads with the origin­al size of the image. We were even lucky be­cause we chose one similar to the dis­play­ing size, but it could be thousands of pixels. So we will set the width of the image.
  • The height of the .element is for­ced to 120px be­cause of the pro­per­ty height: 120pxthat we specified be­fore. Nor­mal­ly, in CSS we won't spec­ify heights and we will allow for the ele­ments to size them­selves. So we just re­move this pro­per­ty.

Siz­ing th­ings

Sett­ing the width of ob­jects is not so easy. Many times you want it to be 100%, so that the ob­jects like im­ages ad­just to the width of the con­tain­er. In this way, if a scre­en is larg­er it will be­come larg­er, not leav­ing empty spaces.

Howev­er, some times we want the ele­ments to size them­selves such as the but­tons or the heights of the ob­jects, so we will not set them. Last­ly, some times you want an ob­ject to be of an specified size in pixels. This is use­ful for th­ings like icons.

When we set the width of an image to 100%, the height will be auto­matical­ly set so that it keeps the pro­por­tions. After fix­ing both of the mis­takes ex­plained above, we have this CSS:

.gallery {
  margin: 10px;
}

.element {
  background: #eee;
  padding: 10px 15px;
}

img {
  width: 100%;
}

Which makes the HTML to look like this:

The last thing that we need is to make sure that the Dis­like but­ton is on the right. Pro­bab­ly we also want it to be red, so we will do so with CSS:

.dislike {
  float: right;
  background: red;
}

Then we copy/paste* our ele­ment in the three of them so we get the ex­pec­ted layout. We used a small siz­ing trick to keep the kitt­en im­ages dif­ferent:

*we will learn later on how to do this pro­per­ly

Enjoy the cats. Here you have the full code:

<div class="gallery">
  <div class="flex three">
    <div>

      <div class="element">
        <img src="http://placekitten.com/320/240">
        <button class="like">Like</button>
        <button class="dislike">Dislike</button>
      </div>
      
    </div>
    <div>
    
      <div class="element">
        <img src="http://placekitten.com/480/360">
        <button class="like">Like</button>
        <button class="dislike">Dislike</button>
       </div>

    </div>
    <div>
    
      <div class="element">
        <img src="http://placekitten.com/640/480">
        <button class="like">Like</button>
        <button class="dislike">Dislike</button>
      </div>
      
    </div>
  </div>
</div>

The CSS:

.gallery {
  margin: 10px;
}

.element {
  background: #eee;
  padding: 10px 15px;
}

img {
  width: 100%;
}

.dislike {
  float: right;
  background: red;
}

Now that you know the basics about layouts with HTML and CSS, you can begin to create your own layouts.

Ex­erc­ise: create these layouts in HTML+CSS in a similar way to the cats layout: