Regra CSS @media
Exemplo
Altere a cor de fundo do elemento <body> para "lightblue" quando a janela do navegador tiver 600px de largura ou menos:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
Mais exemplos de "Experimente você mesmo" abaixo.
Definição e uso
A @media
regra é usada em consultas de mídia para aplicar estilos diferentes para diferentes tipos/dispositivos de mídia.
As consultas de mídia podem ser usadas para verificar muitas coisas, como:
- largura e altura da janela de visualização
- largura e altura do dispositivo
- orientação (o tablet/telefone está no modo paisagem ou retrato?)
- resolução
O uso de consultas de mídia é uma técnica popular para fornecer uma folha de estilo personalizada (design da Web responsivo) para desktops, laptops, tablets e telefones celulares.
Você também pode usar consultas de mídia para especificar que determinados estilos são apenas para documentos impressos ou para leitores de tela (tipo de mídia: impressão, tela ou fala).
Além dos tipos de mídia, também existem recursos de mídia. Os recursos de mídia fornecem detalhes mais específicos para consultas de mídia, permitindo testar um recurso específico do agente do usuário ou dispositivo de exibição. Por exemplo, você pode aplicar estilos apenas às telas maiores ou menores que uma determinada largura.
Suporte ao navegador
Os números na tabela especificam a primeira versão do navegador que suporta totalmente a regra @media.
Property | |||||
---|---|---|---|---|---|
@media | 21 | 9 | 3.5 | 4.0 | 9 |
Sintaxe CSS
@media not|only mediatype and (mediafeature and|or|not
mediafeature) {
CSS-Code;
}
significado das palavras-chave not , only and e :
not: A palavra-chave not inverte o significado de uma consulta de mídia inteira.
only: a palavra-chave only impede que navegadores mais antigos que não suportam consultas de mídia com recursos de mídia apliquem os estilos especificados. Não tem efeito em navegadores modernos.
e: A palavra-chave and combina um recurso de mídia com um tipo de mídia ou outros recursos de mídia.
São todos opcionais. No entanto, se você usar not ou only , também deverá especificar um tipo de mídia.
Você também pode ter diferentes folhas de estilo para diferentes mídias, 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 mídia
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 |
Recursos de mídia
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 |
Mais exemplos
Exemplo
Oculte um elemento quando a largura do navegador for de 600px ou menos:
@media screen and (max-width: 600px) {
div.example {
display:
none;
}
}
Exemplo
Use mediaqueries para definir a cor de fundo para lavanda se a janela de visualização tiver 800 pixels de largura ou mais, para verde claro se a janela de visualização tiver entre 400 e 799 pixels de largura. Se a janela de visualização for menor que 400 pixels, a cor de fundo será 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;
}
}
Exemplo
Crie um menu de navegação responsivo (exibido horizontalmente em telas grandes e verticalmente em telas pequenas):
@media screen and (max-width: 600px) {
.topnav a {
float: none;
width: 100%;
}
}
Exemplo
Use consultas de mídia para criar um layout de coluna responsivo:
/* 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%;
}
}
Exemplo
Use consultas de mídia para criar um site responsivo:
Exemplo
As consultas de mídia também podem ser usadas para alterar o layout de uma página dependendo da orientação do navegador. Você pode ter um conjunto de propriedades CSS que só serão aplicadas quando a janela do navegador for mais larga que sua altura, a chamada orientação "Paisagem".
Use uma cor de fundo azul claro se a orientação estiver no modo paisagem:
@media only screen and (orientation:
landscape) {
body {
background-color: lightblue;
}
}
Exemplo
Use mediaqueries para definir a cor do texto para verde quando o documento for exibido na tela e para preto quando for impresso:
@media screen {
body {
color: green;
}
}
@media print {
body {
color: black;
}
}
Exemplo
Lista separada por vírgula : adicione uma consulta de mídia adicional a uma já existente, usando uma vírgula (isso se comportará como um 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 CSS: consultas de mídia CSS
Tutorial CSS: Exemplos de consultas de mídia CSS
Tutorial RWD: Web design responsivo com consultas de mídia
Tutorial JavaScript: O método window.matchMedia()