What you want to do can be achieved through media
queries :
A media query consists of a type of media and at least one query that limits style sheets using media characteristics such as width, height and color. It is understood as a CSS3 module that allows to adapt the representation of the content to characteristics of the device. Added in CSS3, media queries let content presentation adapt to a specific range of output devices without having to change the content itself.
Media queries execute CSS code if two conditions are met:
- Screen type (optional)
- Additional restrictions (optional) that may be of size, color, resolution, etc.
and its syntax is simple:
@media [tipo-de-pantalla] [(restricción-adicional)] {
/* estilos que se aplicarán sólo para esa pantalla si cumple al restricción de tamaño*/
}
An example using media queries would be like this:
.columna {
width:33%;
float:left;
}
@media (max-width: 500px) {
.columna {
width:auto;
float:none;
}
}
<div class="columna">Columna1</div>
<div class="columna">Columna2</div>
<div class="columna">Columna3</div>
In the code above, 3 columns will be displayed (class .columna
has width 33%) unless the page has less than 500 pixels, in which case three lines will be shown (automatic width and% is removed) float
). To see the effect you will have to click on the "Full screen" button and change the size of the browser.
Alternatively, if you use a library such as Bootstrap , this will simplify everything (although it will also force you to adjust to its predefined sizes). In that case you can use the class .row
and combine them with col-[tamaño]-[columnas]
where [columnas]
is a number from 1 to 12, and tamaño
can be:
- xs (
col-xs-*
): extra small, for mobile screens
- sm (
col-sm-*
): small, for tablet
- md (
col-md-*
): medium, for small computer screens / with low resolution
- lg (
col-lg-*
): large, for large computer screens / with high resolution
Then, using Bootstrap, the code would be simpler:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<div class="row">
<div class="col-xs-12 col-sm-4">Columna 1</div>
<div class="col-xs-12 col-sm-4">Columna 2</div>
<div class="col-xs-12 col-sm-4">Columna 3</div>
</div>