Regla CSS @media
Ejemplo
Cambie el color de fondo del elemento <body> a "azul claro" cuando la ventana del navegador tenga 600 px de ancho o menos:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
Más ejemplos de "Pruébelo usted mismo" a continuación.
Definición y uso
La @media
regla se usa en consultas de medios para aplicar diferentes estilos para diferentes tipos de medios/dispositivos.
Las consultas de medios se pueden usar para verificar muchas cosas, como:
- ancho y alto de la ventana gráfica
- ancho y alto del dispositivo
- orientación (¿la tableta/teléfono está en modo horizontal o vertical?)
- resolución
El uso de consultas de medios es una técnica popular para entregar una hoja de estilo personalizada (diseño web receptivo) a computadoras de escritorio, portátiles, tabletas y teléfonos móviles.
También puede usar consultas de medios para especificar que ciertos estilos son solo para documentos impresos o para lectores de pantalla (tipo de medio: impreso, pantalla o voz).
Además de los tipos de medios, también hay funciones de medios. Las funciones de medios brindan detalles más específicos para las consultas de medios, al permitir probar una función específica del agente de usuario o dispositivo de visualización. Por ejemplo, puede aplicar estilos solo a aquellas pantallas que son más grandes o más pequeñas que un cierto ancho.
Compatibilidad con navegador
Los números de la tabla especifican la primera versión del navegador que es totalmente compatible con la regla @media.
Property | |||||
---|---|---|---|---|---|
@media | 21 | 9 | 3.5 | 4.0 | 9 |
Sintaxis CSS
@media not|only mediatype and (mediafeature and|or|not
mediafeature) {
CSS-Code;
}
significado de las palabras clave not , only and y :
not: la palabra clave not invierte el significado de una consulta de medios completa.
only: la palabra clave only evita que los navegadores antiguos que no admiten consultas de medios con funciones de medios apliquen los estilos especificados. No tiene ningún efecto en los navegadores modernos.
y: La palabra clave y combina una función de medios con un tipo de medio u otras funciones de medios.
Todos son opcionales. Sin embargo, si usa not o only , también debe especificar un tipo de medio.
También puede tener diferentes hojas de estilo para diferentes medios, como esta:
<link rel="stylesheet" media="screen and (min-width:
900px)" href="widescreen.css">
<link rel="stylesheet" media="screen and (max-width:
600px)" href="smallscreen.css">
....
Tipos de medios
Value | Description |
---|---|
all | Default. Used for all media type devices |
Used for printers | |
screen | Used for computer screens, tablets, smart-phones etc. |
speech | Used for screenreaders that "reads" the page out loud |
Funciones multimedia
Value | Description |
---|---|
any-hover | Does any available input mechanism allow the user to hover over elements? (added in Media Queries Level 4) |
any-pointer | Is any available input mechanism a pointing device, and if so, how accurate is it? (added in Media Queries Level 4) |
aspect-ratio | The ratio between the width and the height of the viewport |
color | The number of bits per color component for the output device |
color-gamut | The approximate range of colors that are supported by the user agent and output device (added in Media Queries Level 4) |
color-index | The number of colors the device can display |
grid | Whether the device is a grid or bitmap |
height | The viewport height |
hover | Does the primary input mechanism allow the user to hover over elements? (added in Media Queries Level 4) |
inverted-colors | Is the browser or underlying OS inverting colors? (added in Media Queries Level 4) |
light-level | Current ambient light level (added in Media Queries Level 4) |
max-aspect-ratio | The maximum ratio between the width and the height of the display area |
max-color | The maximum number of bits per color component for the output device |
max-color-index | The maximum number of colors the device can display |
max-height | The maximum height of the display area, such as a browser window |
max-monochrome | The maximum number of bits per "color" on a monochrome (greyscale) device |
max-resolution | The maximum resolution of the device, using dpi or dpcm |
max-width | The maximum width of the display area, such as a browser window |
min-aspect-ratio | The minimum ratio between the width and the height of the display area |
min-color | The minimum number of bits per color component for the output device |
min-color-index | The minimum number of colors the device can display |
min-height | The minimum height of the display area, such as a browser window |
min-monochrome | The minimum number of bits per "color" on a monochrome (greyscale) device |
min-resolution | The minimum resolution of the device, using dpi or dpcm |
min-width | The minimum width of the display area, such as a browser window |
monochrome | The number of bits per "color" on a monochrome (greyscale) device |
orientation | The orientation of the viewport (landscape or portrait mode) |
overflow-block | How does the output device handle content that overflows the viewport along the block axis (added in Media Queries Level 4) |
overflow-inline | Can content that overflows the viewport along the inline axis be scrolled (added in Media Queries Level 4) |
pointer | Is the primary input mechanism a pointing device, and if so, how accurate is it? (added in Media Queries Level 4) |
resolution | The resolution of the output device, using dpi or dpcm |
scan | The scanning process of the output device |
scripting | Is scripting (e.g. JavaScript) available? (added in Media Queries Level 4) |
update | How quickly can the output device modify the appearance of the content (added in Media Queries Level 4) |
width | The viewport width |
Más ejemplos
Ejemplo
Oculte un elemento cuando el ancho del navegador es de 600 px o menos:
@media screen and (max-width: 600px) {
div.example {
display:
none;
}
}
Ejemplo
Use mediaqueries para establecer el color de fondo en lavanda si la ventana gráfica tiene 800 píxeles de ancho o más, a verde claro si la ventana gráfica tiene entre 400 y 799 píxeles de ancho. Si la ventana gráfica tiene menos de 400 píxeles, el color de fondo es azul claro:
body {
background-color: lightblue;
}
@media screen and (min-width:
400px) {
body {
background-color: lightgreen;
}
}
@media
screen and (min-width: 800px) {
body {
background-color: lavender;
}
}
Ejemplo
Cree un menú de navegación receptivo (que se muestra horizontalmente en pantallas grandes y verticalmente en pantallas pequeñas):
@media screen and (max-width: 600px) {
.topnav a {
float: none;
width: 100%;
}
}
Ejemplo
Use consultas de medios para crear un diseño de columna receptivo:
/* On screens that are 992px wide or less, go from four columns to two
columns */
@media screen and (max-width: 992px) {
.column {
width: 50%;
}
}
/* On screens that are 600px wide or less, make the columns stack
on top of each other instead of next to each other */
@media screen and (max-width:
600px) {
.column {
width: 100%;
}
}
Ejemplo
Use consultas de medios para crear un sitio web receptivo:
Ejemplo
Las consultas de medios también se pueden usar para cambiar el diseño de una página según la orientación del navegador. Puede tener un conjunto de propiedades CSS que solo se aplicarán cuando la ventana del navegador sea más ancha que su altura, una orientación denominada "Horizontal".
Use un color de fondo azul claro si la orientación está en modo horizontal:
@media only screen and (orientation:
landscape) {
body {
background-color: lightblue;
}
}
Ejemplo
Use mediaqueries para establecer el color del texto en verde cuando el documento se muestra en la pantalla y en negro cuando se imprime:
@media screen {
body {
color: green;
}
}
@media print {
body {
color: black;
}
}
Ejemplo
Lista separada por comas : agregue una consulta de medios adicional a una ya existente, usando una coma (esto se comportará como un operador OR):
/* When the width is between 600px and 900px OR above 1100px - change the
appearance of <div> */
@media screen and (max-width: 900px) and
(min-width: 600px), (min-width: 1100px) {
div.example {
font-size: 50px;
padding: 50px;
border: 8px solid black;
background: yellow;
}
}
páginas relacionadas
Tutorial de CSS: Consultas de medios CSS
Tutorial de CSS: Ejemplos de consultas de medios CSS
Tutorial de RWD: diseño web receptivo con consultas de medios
Tutorial de JavaScript: El método window.matchMedia()