Category Archives: CSS

The cascading style Sheets Cascading Style Sheets (CSS) are a language of graphic design to define and create the presentation of a structured document written in a markup language, typically web pages written in HTML or XHTML, the language can be applied to any XML document, including XHTML, SVG, XUL, RSS, etc Also allows you to apply styles is not visual, such as style sheets hearing

CSS

CSS

Cascading style sheets (CSS) are a graphic design language for defining and creating the presentation of a structured document written in a markup language, typically web pages written in HTML or XHTML; the language can be applied to any XML document, including XHTML, SVG, XUL, RSS, etc. It also allows you to apply non-visual styles, such as auditory style sheets

A style sheet is nothing more than a text file with a .css extension. Although style sheets were defined in the mid-1990s, they have had a special impact since their latest release (CSS3), in combination with HTML5

Different style sheets can be applied depending on the device on which we display our website (a large screen, a mobile, printed paper, etc)

Integration of styles in a page

There are several ways to integrate styles into a page. But normally we'll use one of these two:

  • Included as a label that is part of the HTML

    The problem with this option is pretty obvious. If in the future we would like to change the color of the paragraphs containing the text, we would have to search one by one for all occurrences and change them manually

  • Defined as a style rule in the header

    On a real web page we'll use more than one style rule, so it won't be a good option to add them one by one in the header

  • Defined with the label <link> to an external file

    Normally we will use more than one style rule, so it will be a good option to add them from an external .css extension file and link them in the HTML header with the tag <link>

Structure of a style sheet

A style sheet defines one or more rules that are applied to items that meet this rule

Each rule consists of two parts:

  • Selector: indicates which elements we're going to apply the rule to. More than one selector can be written for the same rule separated by commas
  • List of statements: the styles to apply to items that comply with the rule. They correspond to a couple property:value, separated by semicolons

The example defined a rule that applies to all paragraph p-elements in the HTML. In addition, the text has been set red, its font as Verdana, and its paragraph alignment is centered

Additionally, we can add comments, which will be written between /* and */

You can also add at directives (which start with a button), which change the way you apply the rules

DOM tree

The document object model (DOM) is the structured, tree-shaped representation of all elements written in an HTML document

For example, any HTML document starts with the tag , also containing the labels and , with their respective closing labels

On the other hand, within the header (label <head>) will in turn contain elements with labels <meta>, <link>, <title>, etc

And the body (label <body>), will in turn contain more elements and so on until it reaches its closing labels

The hierarchical structure resulting in computing is called a tree

Specifically, the tree that represents the structure of an HTML document is DOM

Thanks to this tree-shaped structure, we can uniquely identify each element of the HTML document, depending on how those elements are related to each other, we will be able to apply different style rules to them

The relationships we can identify are:

  • Descendants: are all elements contained (directly or indirectly) by an element

    For example, <head>, <meta> or <body> they are descendants of <html>

  • Direct Son: they are the descendants of first level

    For example, <head> he is the son of <html>

  • Brothers: descendants who have a common father

    For example, all the elements <meta> are brothers if

Thanks to these relationships within the DOM, in the example we used earlier that affected only the elements <p>, we could also apply it to the elements contained in a division <div> that contains a class or an id specific

Or we could create rules for siblings that share a node

By relying on the JavaScript language and the DOM, you can modify the content of the elements once the website is loaded into the browser

Cascading style

Thanks to DOM we can identify the specific elements of an HTML document, and therefore we can apply the style sheets

A style sheet can contain different rules that configure the same element, we can even have multiple style sheets with conflicting rules

In this example, our rules say that for every element of the <body>, including its descendants, will be applied to it the black background color and the red text color

In the following rule, we tell you that in the element <p> paragraph, the text must be blue

The final document will have all the black background color elements and the red text, but in addition the paragraphs will have blue

The rules have been applied to each other, in the form of a waterfall. That's why they are called Cascading style sheets (CSS)

In general, styles are inherited. First they set the property of the parent element and their descendants inherit them, to finally apply their own, which in turn are inherited by their descendants, until they reach the last descendant node of the style sheet

In the event that we have two elements that are brothers and there is conflict to see who inherits which property, the most specific one is applied and if they have the same properties, the last style defined will be applied

That is, if a rule is defined in two external style sheets, the sheet rule that was later included in the HTML document will be applied. That's why the order in which we include them is very important

First we will include the leaves, more general, and then those that are more specific

If you have embedded a rule in the HTML, the style that has been defined will be the one that will have the highest priority than the rule that is included in the HTML header

In short, the following priorities will apply when applying a rule to a particular item:

  1. Finds all the statements that apply to the item
  2. If there are no rules, the inherited value will be used

    If there is no inherited value, the browser will apply the default value

  3. If there are rules, the highest priority will be applied according to the following criteria:

    • A weight is assigned according to its origin: author, user or browser style sheet
    • Attributes with the !important keyword: will have higher priority
    • Specific selectors: will have higher priority
    • Two rules with the same priority: applies the indicated in last place

CSS Reset

Each browser has its own style sheet by default

This implies that the default style of some elements can be different for each browser

For this reason it is advisable to restart the styles applied to the elements by adding a special CSS (the CSS Reset) at the beginning of our web pages

There are multiple CSSs that perform this task (such as those used in frameworks Yahoo YUI, HTML5 BoilerPlate or Normalize), but one of the most popular is Eric Meyer considered as one of the gurus of the CSS

To add it you only have to save the file in the css folder contained in the root of your web site and define it with the tag <link> in the header of your HTML:

Selectors

Selectors

The selectors are used to identify the elements to which it will apply the format defined in the list of statements

There are different types of selectors that can be used to define CSS rules

Let's describe them from the most general to the most specific (from the point of view from lowest to highest priority)

Universal Selector

It is set to * and applies to all elements of the page:



The example has configured the margins and font of the text, which are usually some of the most commonly used rules

Tag Selector HTML

Indicates the style to be applied to an element or a specified tag

Its there's more than one, they'll be separated by commas



In the example, labels 1 to 5 of the title have been set, applying the font of the large text

As can be seen, we can do without < and > the label

Class Selector

Some HTML elements have the attribute class that indicates the classes to which the element belongs

This attribute allows us to treat that element "class" in a specific way, both in css style application and in its behavior programmatically with JavaScript

To apply the class selector, we'll use tag.class

In the example, we have configured the text in blue color for all the elements of the header class, because if we do not specify a label, the universal selector *

In the example you have set the text alignment centered only for the elements of the class header, which belong to the title tag <h1>

We must take special care not to leave spaces between the label, the point and the name of the class, since that space is significant, as we will see later

Selector id

Some HTML elements have the id attribute that indicates that this unique identifier it belongs to that particular element

To apply the identifier selector, we'll use tag#id

As with classes, it is very important to use the spaces

The example has set the background color of the text to yellow, in that paragraph that has the featured identifier

Selectors, descendant, and adjacent

These selectors allow you to select elements that are contained within other according to the structure of the DOM tree

This is where spaces take importance, because if we separate two selectors with a space, then we will be applying the rule to all descendants of the first selector

In the example you have set the text font as Verdana for all the elements <p> that they are descendants of the element <section> (remember that they can be descendants of any level, since that rule will be inherited)

Can be mixed interchangeably selectors descendants of a class or id

In the example, we have configured the text color as red for any element of the class error that is a descendant of the element

If instead of applying it to all descendants we want it to only apply to direct descendants (children), then we will use the >

In the example, we have configured the font of the text as Verdana only for the items <p> that are children of the element <section>

We can also select the sibling elements, that is, those that appear right after other elements, then we will use the symbol +

In the example, we have configured the indentation of the first paragraph that appears just after the title tag <h1>

Selectors of attributes

These selectors are used to select elements based on their attributes

There are four types:

  1. [attribute]: elements that have an attribute named attribute, regardless of its value
  2. [attribute=value]: elements that have an attribute named attribute with the specified value
  3. [attribute^=value]: elements that have an attribute named attribute and whose value starts with the specified value
  4. [attribute$=value]: elements that have an attribute named attribute and whose value ends with the specified value

In the example, we have set up a link that we want in a different color if it leads to a url with secure HTTP

Pseudo-classes

There are selectors special to specify elements that have certain properties

They are classes virtual, because they are not specified in HTML, but represent the positions or states in which an item can be found while viewing in the browser

The example has been configured to apply only if an item is the first child of its parent, for this we have used the first-child pseudoclass, only the first element <li> from a bullet list (<ul>) will appear in green

There are other pseudoclasses that will help us select a specific brother from among the children of an element:

  • :nth-child(n) : represents the n-th brother

    It allows you to include a more complex form such as:

    • :nth-child(even) : that represents the children who occupy positions pairs
    • :nth-child(odd) : that represents the children that occupy odd positions

    (for example to make odd rows in a table have different background color and have a hebrew effect on a table)

  • :nth-last-child(n) : similar to the previous one, but starting to count from the end

There are also dynamic pseudoclasses, which indicate the status of items when the user interacts with them:

  • :hover : is used to set the style when the user mouses over the element
  • :active : is used to set the style when the user click on the item or keep the mouse button pressed over it
  • :focus : is used to set the style when the element has focus

Pseudoclasses related to links are also very typical:

  • a:link : sets the style of the link when it has not yet visited or when the user has not already pressed
  • a:hover : set the style when the user places the mouse over the link element
  • a:active : set the style when the user clicks the link
  • a:visited : set the style when the user has already visited

The example has set the status of unvisited, visited or mouse-based links

When using this CSS, the links in the document will appear un underlined and green

By placing the mouse over them they will stop at blue and, once visited, they will turn red

Example of Selectors in action

In the following example has included an HTML page and several of the selectors explained above

You can check the result by viewing it yourself in your browser and if you don't use a CSS reset, you might have different results in other browsers

Now we show the contents of the exampleSelectors.css file

Positioning of elements

Positioning of elements

Positioning 'classic' elements is based on the model of blocks, which are placed to fill the page space from left to right and top to bottom

However, this model does not adapt well on mobile devices, where we will encounter problems with the size, orientation in the browser and even in the reordering of the elements to fit the type of device

To solve these problems appeared model of flexible positioning, which simplifies these tasks considerably

However, this model is too detailed to organize the overall structure of the website

For that reason, the model grid, which divides the space into a virtual grid and creates an array divided into cells within that grid, assigning the elements to a particular cell that will occupy so many additional cells depending on the size and orientation of the device

These two models are supported in addition to the so-called responsive design, which allows our website to adapt to the device on which it will be viewed: smartphones, tablets or desktop PCs

Model block

The boxes of the elements are placed by default following the 'normal flow', that is, pushing the boxes left and up

You can use the property position to modify the 'normal flow‘:

  • position: static it is the mode of positioning by default
    The box will occupy the position of the 'normal flow
  • position: relative using the properties top, right, bottom and left move your position
    These dimensions indicate the spacing that is left to each side in accordance with the original position of the box
    The rest of the boxes are not affected by this displacement, so they respect their reserved space
  • position: absolute it removes the box from the normal flow and placed the new box in a fixed position with respect to its containing box
    Supports the properties top, right, bottom and left
    You can overlap other elements because it is not respecting your space reserved
  • position: fixed similar to absolute positioning, but you specify the position relative to the window
    This implies that the box maintains its position and does not move when using the scroll bar
  • position: float the box is shifted to one side using the properties left or right, moving it to one end of the containing box or to the first floating box it finds in that direction
    May overlap with other elements that are not floating boxes
  • clear will only apply if there are floating boxes, for force the item to be displayed under the floating box of a certain type with the properties left or right; or anyone with both

Let's use this sample html to be able to check the use of the block model, for this we will use as a basis, the following sample style sheet:

A large font size was intentionally used to force scrolling. Now perform the following exercise so you can check for yourself how the block model works:

  1. Change the positioning of the block a a relative and asignale spacing top of 1em and a spacing left of 2em

    The blue block will overlap the red block, but the reserved space that should have occupied the blue block is preserved
  2. Change the positioning of the block c a relative and asignale spacing top of 1em and a spacing left of 2em

    The pink block will change its position relative to its container (the red block)
  3. Change the positioning of the block a a absolute and asignale spacing top of 1em and a spacing left of 2em

    The blue block will overlap the red block, but since no space has been reserved for the blue block, the red will be placed in the upper left corner
    And if we scroll, the blocks will no longer be visible
  4. Change the positioning of the block a a fixed and asignale spacing top of 1em and a spacing left of 2em

    The blue block will overlap the red block, but since no space has been reserved for the blue block, the red will be placed in the upper left corner
    And if we scroll, we will see that the blue block has been fixed in its position with respect to the window
  5. Change the positioning of the block a a float: right

    The blue block will overlap the other elements, have been placed on the right edge of the screen and no space has been reserved for that block
  6. Change the positioning of the block c a float: right

    The pink block will stick to the right side of your container, the red block
  7. Change the positioning of the block b a float: right

    The red block will stick to the right side of the previous floating element, the blue block
  8. Change the positioning of the block a a float: left and added to p the property clear: right

    The paragraph will be placed under the red block, but will overlap the blue block
  9. Change the positioning of p a clear: both

    The paragraph will be placed below the blue block

Flexible model

The flexible positioning allows you to accommodate the elements of the page according to changes in the dimensions and orentación of the page

It allows us to make a responsive design for our web pages you envisage properly in any device

This standard is relatively recent and is not yet supported by all browsers, but in the future it will be

As advantages you get a more readable and simple code, where you can change the order of the elements regardless of the order in the HTML code

The flexible model is appropriate for placing small components of a web page

To make a general arrangement of the elements of the page, the grid model is being imposed

The main idea is that a flexible container expands or compresses to fill the free space or to fit the available area

So we'll have a flex container and a series of flex item

To define a container, we will use the property display: lex (or display: kit-web.flex if we want Safari support)

All the elements will be elements flex

This model does not use concepts such as horizontal or vertical sorting, but defines a main axis and a secondary axis (cross axis)

This easily adjusts the design to the device's orientation changes

For each axis we can place the components at their start (main-start or cross-start) y final (main-end or cross-end)

Let's use this sample html to be able to check the use of the flexible model, for this we will use as a basis, the following sample style sheet:

Direction of the elements

The property flex-direction specifies the direction of the main axis, that is, how elements are placed inside the container

Supports the following values:

  • row
  • row-revese
  • column
  • column-reverse

To check its behavior, add the following CSS to the previous example:

Fit in the main shaft

The property wrap sets whether items need to be adjusted for display in a single row (or column)

Supports the following values:

  • nowrap adjust the elements to a line
  • wrap adjusts the items but without changing its size
  • wrap-reverse adjusts the elements but without resizing them, but in the reverse order of rows

To check its behavior, add the following HTML to the previous example:



And the following CSS:

Alignment of the content

With the property justify-content we can align the elements with respect to the main axis of the container

Allows us to decide what to do with the remaining space

Supports the following values:

  • flex-start board items at the beginning of the axis
  • flex-end board items at the end of the shaft
  • center centers the elements
  • space-between divides the space between the elements, leaving the ends attached to the edge
  • space-around all of the remaining space is distributed around each element

To check its behavior, add the following HTML to the previous example:



And the following CSS:

Fit on the secondary axis

To align the elements with respect to the secondary axis, we have the property align-items

Supports the following values:

  • strech to occupy all the width
  • flex-start aligns elements to the beginning of the axis
  • flex-end aligns items to the end of the shaft
  • center centers the elements

To check its behavior, add the following HTML to the previous example:

And the following CSS:

Properties of the elements

Up to now we have seen properties to configure the main container

Now let's list some very interesting properties to manipulate the elements:

  • order indicates the order in which they appear the element within the container
    In this way it will not be necessary to modify the HTML to reorder the elements, since we will do it by code
  • flex-grow sets the growth factor item
    That is, how it grows in relation to the other elements, as long as the container has free space
  • flex-shrink sets the factor of shrinkage item
    That is, how it decreases in relation to the other elements, as long as the container has free space
  • flex-basis indicates the default size (width) before the free space of the container is distributed
    Normally its default value is left: flex-basis: auto

There is a short form for the properties flex-grow, flex-shrink and flex-basis, simply specifying the value they will take: flex: 1 1 auto

To check its behavior, add the following HTML to the previous example:

And the following CSS:

Model grid

Although the box model flexible allows you to create sites adaptive thanks to the media queries, the model that is being imposed is the grid

In this model, the screen is divided into a grid is virtual, and the designer can choose how many cells of that grid will occupy each element depending on the device

This design has been popularized thanks to Bootstrap created by the developers of Twitter

In Bootstrap the available space is divided into 12 columns of equal size

For each item indicate how many columns will occupy depending on the size of the device

For example, for a sidebar we can indicate that it occupies 2 columns on a desktop, 6 columns (half the total width) for tablets and 12 columns (the entire width) on mobile devices

To achieve this, a set of classes will be used, in this example they would be: .col-md-2, .col-sm-6 and .col-xs-12

Sizes are defined in Bootstrap how to:

  • xs (extra small)
    Screens with width lower than 768px format
    The vast majority of smart phones
  • sm (small)
    Screens with a width less than 992px
    If the xs class has been defined and the size less than 768px, then that class will be applied
  • md (medium)
    Screens between 992px and 1200px
    This range represents the majority of desktop browsers
  • lg (large)
    Screens very big with a width over 1200px
    They are usually large high-definition screens

As you can see in the example, the content is organized into rows (row class) and within these rows we will create the columns with the desired sizes

Media Queries

A media query allows you to use the rules of style sheets depending on the characteristics of the medium (width, height and color)

They were added from CSS3, allow the presentation of the content to adapt to a specific scrape of output devices without having to change the contents and are the basis of adaptive design

They can be used in two ways: by importing a style sheet or by applying them within the same style sheet

Importing style sheets

We can use the media queries to choose different CSS depending on the medium or the characteristics of the same

Currently there are only two supported means:

  • screen a browser
  • print a printer

As can be seen in the example, defining the media type is as simple as adding the attribute media within the element link

It is also possible to indicate conditions about the media type, in the example we have told you to load when the media has a width less than 800px, so that you can use it with tablets

Rules @media

The rules @media allow us to indicate on what media type should apply certain CSS rules

Its generic sintasix is:

The only mediatype supported are screen and print, as we've seen before

As can be seen in the example, media feature allow us to indicate characteristics of the device, and you can add conditions by using logical operators and, not and only

We can using the media feature specify the size of the device, its temptation or resolution, number of colors, etc

Some of the highlights are:

  • aspect-ratio width/height of the device
  • min-aspect-ratio minimum width/height of the device
  • max-aspect-ratio maximum width/height of the device
  • color-index number of colors the device can display
  • width exact width
  • min-width minimum width
  • max-width maximum width
  • height high exact available
  • min-height minimum height available
  • max-height high maximum available
  • orientation orientation, supports values:
    • landscape
    • portrait

Adaptive layout with Media Queries

Let's see two examples with media queries to understand how to make our own adaptive designs, one with the flexible model and another with the model grid

Adaptive layout with the flexible model

In the following example, we create an adaptive layout with the flexible model is very easy

Because we can take advantage of the possibility to reorder the items on that offers us this option

Let's start from a 3-column layout with the navigation bar, the main content and a sidebar

When the size of the browser is less than 640px will go to a single column

The HTML we'll use in the example is as follows:

The CSS code in the flexible.css file that we'll use in the example is as follows:

Adaptive design with the model grid

In the following example, we create an adaptive layout with the model grid is very easy

One of the main limitations is that no longer that we can reorder the elements

We are going to use a grid of type Bootstrap

To do this we will use the classes cols-xs-12 to indicate that in small size the element will occupy 12 columns, col-sm-8 will occupy 8 columns for a small size and col-sm-2 will occupy 2 columns for a slightly larger size

For the change of size small to large has been assigned 768px format

The HTML we'll use in the example is as follows:

The CSS code in the grill.css file that we'll use in the example is as follows:

Lists of CSS declarations

Lists of CSS declarations

Properties are defined as lists of CSS declarations, they are very heterogeneous and cannot be applied to all HTML tags

We can find examples in w3schools or in MDN Web Docs Mozilla

Below we will address some of the main lists of statements

Units of measure

Many properties accept as the value of a unit of measure

En general, es recomendable utilizar medidas relativas en vez de absolutas

For example, for a web page we could indicate that we want 20 pixels high, however, if our users change devices, such as a mobile or a tablet, that size would be too large or the content would appear disproportionate.

To avoid that or similar problems, CSS declarations support the following units:

  • Percentage: sets the size in percent with respect to the inherited value
  • em: sets the size according to the current font (or the legacy font, if no font size is defined)
  • px: sets the size in pixels (a pixel represents a specific point on the screen that shows our page), being an absolute measure, as it can cause problems, we should limit its use to specific cases

We may use CSS declarations to indicate the visual appearance of the web page on different devices, such as a printer. For those cases we can use other types of measures:

  • cm, mm, in: the size is set to one of the international units (cm for centimeters, mm for millimeters, and in for inches)
  • pt: the size is set in points (one point equals \frac{1}{72} inch)

The use of relative measures (percentages or em) allow our page to be displayed correctly on any device. This practice is called design adaptive or responsive, that is, our design will adapt to the device on which it is viewed (a browser, a mobile, a tablet, etc.)

Colors

Another of the fundamental elements for a web page is the treatment of the colors

There is a list of 140 basic colors that we can find predefined, we can also define them manually using the RGB notation (Red, Green, Blue) to indicate the amount of red, green and blue that make up that color

To define the color we will use a value between 0 and 255 (in its value hexadecimal), starting the encoding with the '#' symbol followed by a 6 digit hexadecimal number

We can define color in the following ways:

  • color: value where value is one of the predefined colors
  • colour: code dónde código es un valor que empieza por el símbolo ‘#’ seguido de un número hexadecimal de 6 cifras
  • color: RGB(entero, entero, entero): dónde RGB es una función que admite 3 valores entre 0 y 255 que corresponden a la cantidad de rojo, verde y azul que componen ese color
  • color: RGB(entero%, entero%, entero%): igual que la anterior, pero el valor entero es un porcentaje
  • color: transparent: the color transparent is also a valid color in CSS3

Text properties

Las principales propiedades que se pueden utilizar en los elementos de texto son:

  • color

    indica el color de la fuente. Su valor es un color, ya lo hemos descrito en el previous paragraph

  • font-size

    representa el tamaño de la fuente, como ya se ha descrito en el previous paragraph it is recommended to use relative values

  • font-style

    admite un estilo de letra para el texto, podemos elegir entre uno de los siguientes estilos:

    • normal es el estilo por defecto del navegador, si no se especifica, se tomará este valor
    • italic it is the default style of the browser for the letter in italics
    • oblique es el estilo por defecto del navegador para la letra oblique, es similar a la cursiva, si la fuente no permite el tipo oblique tomará el estilo como italic
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • font-weight

    supports a bold font style for the text, we can choose between one of the following bold types:

    • normal is the default bold of the browser, if not specified, this value will be taken
    • bold defines the bold with bold
    • bolder defines the bold font with the characters more thick
    • lighter defines the bold with the characters thinner
    • integer define la negrita con un valor múltiplo de 100, con el valor 400 por defecto y el 700 para bold
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-decoration-line

    establece el tipo de decoración del texto para el subrayado, podemos elegir entre uno de los siguientes tipos de decoración:

    • none valor por defecto del navegador, si no se especifica, se tomará este valor
    • underline the underline will be below the text
    • overline the underline will be on the text
    • line-through the underscore will be through text
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-decoration-color

    establece el color para la decoración del texto, podemos elegir entre uno de los siguientes tipos de decoración:

    • color where color is one of the values seen in the previous paragraph
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-decoration-style

    establece el tipo de decoración del texto, podemos elegir entre uno de los siguientes tipos de decoración:

    • solid valor por defecto del navegador, si no se especifica, se tomará este valor. Mostrará la línea en una única línea
    • double show the line with a double line
    • dotted show the line as a dotted line
    • dashed show the line as a dashed line
    • wavy show the line as a wavy line
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • text-transform

    establece el texto en letras minúsculas o mayúsculas, podemos elegir entre uno de los siguientes tipos de transformación:

    • none valor por defecto del navegador, si no se especifica, se tomará este valor. No se tomarán letras mayúsculas
    • capitalize transforms the first letter of each word to uppercase
    • uppercase transform all letters to uppercase
    • lowercase transform all letters to lowercase
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
  • letter-spacing

    aumenta o disminuye el espacio entre caracteres en un texto, podemos elegir entre uno de los siguientes:

    • normal valor por defecto del navegador, si no se especifica, se tomará este valor. No hay espacios extra
    • length dónde lenghth es la cantidad de espacios extra entre caracteres (también están permitidos valores negativos)
    • initial is used to set a CSS property to its default value
    • inherit is used to inherit a property value from its parent element
    • word-spacing

      aumenta o disminuye el espacio entre las palabras en un texto, podemos elegir entre uno de los siguientes:

      • normal valor por defecto del navegador, si no se especifica, se tomará este valor
      • length dónde length es la cantidad de espacios extra entre palabras (también están permitidos valores negativos)
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element
    • line-height

      especifica la altura de una línea, podemos elegir entre uno de los siguientes:

      • normal valor por defecto del navegador, si no se especifica, se tomará este valor
      • number where number is a value that will be multiplied by the current font size to set the height of the line
      • length dónde length es la altura para esa línea (también están permitidos valores negativos)
      • % is the height for that line, in percentage of the size of the current font
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element
    • text-align

      especifica la alineación horizontal del texto en un elemento, podemos elegir entre uno de los siguientes:

      • left the text is aligned to the left
      • right the text is aligned to the right
      • center the text is aligned centered
      • justify el texto las líneas son estiradas para que cada línea tenga el mismo ancho (como en los periódicos y las revistas)
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element
    • text-indent

      especifica la sangría de la primera línea en un bloque de texto, podemos elegir entre uno de los siguientes:

      • length dónde length es la sangría de la primera línea en un bloque de texto (también están permitidos valores negativos, en ese caso se usará una sangría a la izquierda)
      • % is the indentation of the first line in a block of text in percentage of the size of the parent element
      • initial is used to set a CSS property to its default value
      • inherit is used to inherit a property value from its parent element

    Es muy importante definir una fuente que sea coherente con el estilo de nuestra web. Para ello se dispone de la propiedad font-family, en la cual especificaremos la fuente (verdana, arial, time new roman, etc) que será usada para ese texto

    Sin embargo nos encontraremos con un problema si esa fuente en concreto no está definida en el navegador, por eso es recomendable especificar varias fuentes en caso de que no existiera alguna de ellas

    Another limitation is that we can only use sources that meet standards allowed by the browsers

    To solve problems related to the sources there are servers text sources they offer the possibility to load the font that we need of that server

    In the above example we have used one of the reference sources from Google called Roboto, and we have added to our header

    Background properties

    To set the background of an element we will use the property background-color

    Can also be used as a background image using the property background-image, que se repetirá vertical y horizontalmente para cubrir todo el elemento

    We may limit the way in which it repeats that image with the properties background-repeat: repeat-y and background-repeat: repeat-x

    In the example above we have used the property background-repeat: no-repeat para desactivar la repetición de la imagen, estableciendo además una posición fija, en la esquina inferior derecha, con la propiedad background-position: right bottom

    Para mantenerla fija y que haga scroll en la página, se ha utilizado la propiedad background-attachment: fixed

    Dimensions and edges

    To indicate the dimensions of an element, we use the properties width and height

    We have to take into account if their margins are internal or external

    To do this we first define the margin from the edge to the other elements with the property margin

    In the second place, we define the inner margin to the edge of the item with the property padding

    We can assign an outer margin to the four sides of the property margin or we can tell an outer margin, in particular, for each side using margin-top, margin-bottom, margin-left or margin-right

    De forma análoga, se puede realizar para los márgenes internos utilizando padding-top, padding-bottom, padding-left or padding-right

    Una vez difinidos los márgenes externos e internos, podremos configurar la apariencia que tomará el borde

    First we will establish the style with the property border-style, la cual admite los valores dotted, dashed, solid or double

    También es posible usar valores para crear bordes biselados, pero las guías de estilo modernas desaconsejan su uso por estar “pasados de moda”

    In the second place, we are able to customize the width of the stroke with the property border-width and your color with border-color

    Properties for lists

    Podemos utilizar las siguientes propiedades para manejar elementos lista:

    • list-style-type: representa el tipo de marcador que se utilizará en la lista
      Existen estos valores predefinidos:

      • circle
      • square
      • decimal
      • lower-roman
      • upper-roman
      • none
    • list-style-position: indica si el marcador se incluirá dentro del texto (propiedad inside) o fuera (propiedad outside), siendo esta última la más habitual
    • list-style-image: permite añadir una imagen como marcador
      We may use the values none or url(‘url de la imagen’)

    Other properties

    Además de las propiedades anteriores vamos a destacar un par más que nos serán de especial utilidad a la hora de dar formato a nuestros elementos:

    • visibility: indica si el elemento está visible o no
      Puede tomar uno de los siguientes valores:
      • visible: el elemento está visible
      • hidden: el elemento está no visible
      • collapse: solo podremos usarlo con los elementos de tablas para no visualizar una fila o una columna concreta
    • display: cambia el tipo de caja del elemento, puede tener los valores:
      • block
      • inline
      • none

Preprocessors CSS

Preprocessors CSS

El uso de procesadores CSS surge por un problema muy común en las hojas de estilo, muchos valores se repiten constantemente

Como podemos ver en el ejemplo anterior, el color #C0392B se repite constantemente en el código porque es nuestro color principal en este diseño

¿Pero, y si necesitamos cambiarlo? Esa situación nos obligaria a cambiar todas sus apariciones en la hoja de estilo

In the example above, it has solved the problem with the variable colorPrincipal, sin embargo, esta solución no es permitida por el CSS estándar

Therefore arises the need for the use of processors CSS, que son aplicaciones que permiten dotar al CSS de las ventajas de un lenguaje de programación, como el uso de variables, funciones, condiciones e incluso cálculos matemáticos, los cuales serán traducidos posteriomente a un CSS válido

No existe un estándar claro para este tipo de procesadores, pero tenemos las siguientes alternativas:

  • Sass funciona con Ruby, el cual viene preinstalado en Mac; si eres usuario de Windows necesitaras instalar previamente Ruby
    Funciona mediante línea de comandos en un terminal, ya que no tiene entorno gráfico
    Si quieres usarlo en modo visual, existen varias herramientas de pago que podrian interesarte
  • LESS está escrito en javascript, por lo que su instalación es tan sencilla como su importación directamente a nuestro documento HTML
    There are free tools that help to compile your files written in LESS, a CSS valid
    Aunque puede configurarse LESS para que haga el proceso de compilación ‘the flight‘, aunque no es recomendable porque consume tiempo de carga cada vez que recompila
  • Stylus necesitaremos instalar previamente Node.js, el cuál tiene su propio conjunto de repositorios que permite tener siempre la última versión estable del programa
    Funciona mediante línea de comandos en un terminal, ya que no tiene entorno gráfico
    Si quieres usarlo en modo visual, existen varias herramientas de pago que podrian interesarte

La sintaxis de estas herramientas es similar aunque hay pequeñas diferencias entre ellas, ya que como se ha dicho, no hay un estándar para preprocesadores CSS

LESS

Installation

With this tool we will create files .less where you keep our CSS rules improved

We'll include LESS in our HTML using the import Javascript and it will translate the file .less in a .valid css that will be loaded in the HTML page

Este tipo de instalación usada sólo en desarrollo es considerada ‘the flight‘ y llamada compilación, por motivos de eficiencia, en la página de producción, se añadirá el .css válido y ya traducido

Para poder realizar esta traducción ‘the flight‘ añadiremos las siguientes líneas en el head de nuestro HTML:

En el ejemplo nuestro fichero LESS se llama mystyle.less y le hemos indicado al navegador que es una hoja de estilos LESS con la referencia ‘stylesheet/less’

Despues hemos cargado la libreria Javascrip de LESS llamada less.js, que será la encargada de traducir el archivo mystyle.less al CSS válido y lo cargará en el HTML

Variables

Antes hemos visto un ejemplo para definir una variable para el color, en LESS se definen las variables con el símbolo @

Mixins

Mixins allow a CSS rule to inherit all the declarations of other

En el ejemplo anterior hemos hecho que los elementos p, ul y ol incluyan todas las declaraciones de .block y así nos ahorramos el tener que volver a escribirlas en cada aparición

Mixins also allow the use of parameters to configure them

En el ejemplo anterior hemos definido el mixin error donde el ancho de borde es configurable con la variable @wideBorder

Si no hay parámetros, su valor por defecto será 2px, como se ha indicado en su definición

.error-generic llama al mixin para heredar todas las declaraciones y, como no tiene parámetros toma su valor por defecto

.error-login llama al mixin pero esta vez, como tiene un parámetro toma el valor del mismo

Legacy code

A veces surge el problema de tener varios elementos con el mismo padre, con lo que nos vemos obligados a repetir en cada aparición referencias al padre

En el ejemplo anterior tenemos el problema comentado, section es el padre en la mayoría de los elementos de la hoja de estilo, a su vez nav es padre de varios de ellos, al igual que a

En el ejemplo anterior lo hemos solucionado escribiendo anidaciones de los hijos dentro de los elementos padre, así nos ahorramos repetir las referencias

Además permite usar el símbolo & para referirse al elemento padre inmediato dentro del elemento hijo

Functions for the color

The functions for the color to change the color at compile time

Son bastante útiles para crear degradados, oscurecer botones al pasar el ratón, etc

Operations

LESS allows mathematical operations

Como se puede ver en el ejemplo, no tiene muchas restricciones, ya que permite hacer cosas sin sentido como mezclar distintas unidades

Media queries

One of the problems of the media queries is that we can have different definitions of the same class in disintos points of the CSS file

Podemos anidar los media queries dentro de la misma clase, solucionando el problema del ejemplo anterior

Modification of styles

Modification of styles

JQuery allows to modify easily the styles and the CSS properties of our web page

Add or remove CSS properties

By using the methods addClass() and removeClass() we can assign or remove a CSS class from any element

In the example, add the styles are important and color the element with id div01 when you press the button btn01, and eliminates the color style

Manipulation of CSS properties

The method css() allows us to view or modify any property of the stylesheet of an HTML element

It has the following syntax:

In case you only want to see the property, we will omit the parameter value and if we want to modify it, we'll use that parameter

In the example, we have used three paragraphs different with a style for the background color different, if you push the button with id btn03 we can see that with the css method, we have changed all the paragraphs to yellow