Twitter Bootstrap 3: ¿cómo utilizar media queries?


Estoy usando Bootstrap 3 para construir un diseño responsivo donde quiero ajustar algunos tamaños de fuente de acuerdo con el tamaño de pantalla. ¿Cómo puedo usar media queries para hacer este tipo de lógica?

Author: Rui, 2013-08-25

15 answers

Bootstrap 3

Aquí están los selectores utilizados en BS3, si desea mantenerse consistente:

@media(max-width:767px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Nota: Para su información, esto puede ser útil para depurar:

<span class="visible-xs">SIZE XS</span>
<span class="visible-sm">SIZE SM</span>
<span class="visible-md">SIZE MD</span>
<span class="visible-lg">SIZE LG</span>

Bootstrap 4

Aquí están los selectores usados en BS4. No hay un ajuste "más bajo" en BS4 porque "extra small" es el valor predeterminado. Es decir, primero codificaría el tamaño XS y luego tendría estos medios anulados después.

@media(min-width:576px){}
@media(min-width:768px){}
@media(min-width:992px){}
@media(min-width:1200px){}

Actualización 2018-05-03: La información de BS3 sigue siendo precisa a partir de la versión 3.3.7, actualizado BS4 para nueva cuadrícula lanzado en 4.1.1.

 609
Author: William Entriken,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-04 02:01:42

Basado en la respuesta de bisio y el código de Bootstrap 3, pude encontrar una respuesta más precisa para cualquiera que simplemente busque copiar y pegar el conjunto completo de consultas de medios en su hoja de estilos:

/* Large desktops and laptops */
@media (min-width: 1200px) {

}

/* Landscape tablets and medium desktops */
@media (min-width: 992px) and (max-width: 1199px) {

}

/* Portrait tablets and small desktops */
@media (min-width: 768px) and (max-width: 991px) {

}

/* Landscape phones and portrait tablets */
@media (max-width: 767px) {

}

/* Portrait phones and smaller */
@media (max-width: 480px) {

}
 241
Author: Chris Clower,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-27 15:02:28

Si está utilizando LESS o SCSS/SASS y está utilizando una versión de Bootstrap de LESS/SCSS, también puede usar variables, siempre que tenga acceso a ellas. Una traducción MENOS de la respuesta de @full-decent sería la siguiente:

@media(max-width: @screen-xs-max){}
@media(min-width: @screen-sm-min){}  /* deprecated: @screen-tablet, or @screen-sm */
@media(min-width: @screen-md-min){}  /* deprecated: @screen-desktop, or @screen-md */
@media(min-width: @screen-lg-min){}  /* deprecated: @screen-lg-desktop, or @screen-lg */

También hay variables para @screen-sm-max y @screen-md-max, que son 1 píxel menos que @screen-md-min y @screen-lg-min, respectivamente, típicamente para usar con @media(max-width).

EDITAR: Si está utilizando SCSS/SASS, las variables comienzan con un $ en lugar de un @, por lo que sería $screen-xs-max etc.

 132
Author: carpeliam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-09 19:00:49

Estos son los valores de Bootstrap3:

/* Extra Small */
@media(max-width:767px){}

/* Small */
@media(min-width:768px) and (max-width:991px){}

/* Medium */
@media(min-width:992px) and (max-width:1199px){}

/* Large */
@media(min-width:1200px){}
 44
Author: shlomia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-09 10:23:10

Aquí hay dos ejemplos.

Una vez que el viewport tenga 700px de ancho o menos, haga que todas las etiquetas h1 sean 20px.

@media screen and ( max-width: 700px ) {
  h1 {
     font-size: 20px;
  }
}

Haga todos los 20px del h1 hasta que la ventana alcance 700px o más.

@media screen and ( min-width: 700px ) {
  h1 {
     font-size: 20px;
  }
}

Espero que esto ayude: 0)

 29
Author: Jeffpowrs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-25 03:19:37

Aquí hay un ejemplo más modular usando LESS para imitar Bootstrap sin importar los archivos less.

@screen-xs-max: 767px;
@screen-sm-min: 768px;
@screen-sm-max: 991px;
@screen-md-min: 992px;
@screen-md-max: 1199px;
@screen-lg-min: 1200px;

//xs only
@media(max-width: @screen-xs-max) {

}
//small and up
@media(min-width: @screen-sm-min) {

}
//sm only
@media(min-width: @screen-sm-min) and (max-width: @screen-sm-max) {

}
//md and up
@media(min-width: @screen-md-min) {

}
//md only
@media(min-width: @screen-md-min) and (max-width: @screen-md-max) {

}
//lg and up
@media(min-width: @screen-lg-min) {

}
 20
Author: internet-nico,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-18 21:32:18

A partir de Bootstrap v3. 3. 6 se utilizan las siguientes consultas de medios que se corresponden con la documentación que describe las clases responsivas que están disponibles (http://getbootstrap.com/css/#responsive-utilities).

/* Extra Small Devices, .visible-xs-* */
@media (max-width: 767px) {}

/* Small Devices, .visible-sm-* */
@media (min-width: 768px) and (max-width: 991px) {}

/* Medium Devices, .visible-md-* */
@media (min-width: 992px) and (max-width: 1199px) {}

/* Large Devices, .visible-lg-* */
@media (min-width: 1200px) {}

Consultas de medios extraídas del repositorio de GitHub de Bootstrap de la siguiente less archivos:-

Https://github.com/twbs/bootstrap/blob/v3.3.6/less/responsive-utilities.less https://github.com/twbs/bootstrap/blob/v3.3.6/less/variables.less

 20
Author: Suleman C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-20 12:20:26

Basado en las respuestas de los otros usuarios, escribí estos mixins personalizados para un uso más fácil:

Menos entrada

.when-xs(@rules) { @media (max-width: @screen-xs-max) { @rules(); } }
.when-sm(@rules) { @media (min-width: @screen-sm-min) { @rules(); } }
.when-md(@rules) { @media (min-width: @screen-md-min) { @rules(); } }
.when-lg(@rules) { @media (min-width: @screen-lg-min) { @rules(); } }

Ejemplo de uso

body {
  .when-lg({
    background-color: red;
  });
}

Entrada SCSS

@mixin when-xs() { @media (max-width: $screen-xs-max) { @content; } }
@mixin when-sm() { @media (min-width: $screen-sm-min) { @content; } }
@mixin when-md() { @media (min-width: $screen-md-min) { @content; } }
@mixin when-lg() { @media (min-width: $screen-lg-min) { @content; } }

Ejemplo de uso:

body {
  @include when-md {
    background-color: red;
  }
}

Salida

@media (min-width:1200px) {
  body {
    background-color: red;
  }
}
 18
Author: damd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-23 09:43:45

O simple Sass-Compass:

@mixin col-xs() {
    @media (max-width: 767px) {
        @content;
    }
}
@mixin col-sm() {
    @media (min-width: 768px) and (max-width: 991px) {
        @content;
    }
}
@mixin col-md() {
    @media (min-width: 992px) and (max-width: 1199px) {
        @content;
    }
}
@mixin col-lg() {
    @media (min-width: 1200px) {
        @content;
    }
}

Ejemplo:

#content-box {
    @include border-radius(18px);
    @include adjust-font-size-to(18pt);
    padding:20px;
    border:1px solid red;
    @include col-xs() {
        width: 200px;
        float: none;
    }
}
 12
Author: user956584,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-04 22:26:07

Tenga en cuenta que evitar el escalado del texto es la razón principal por la que existen diseños responsivos. toda la lógica detrás de los sitios receptivos es crear diseños funcionales que muestren efectivamente su contenido para que sea fácilmente legible y utilizable en múltiples tamaños de pantalla.

Aunque es necesario escalar el texto en algunos casos, tenga cuidado de no miniaturizar su sitio y perder el punto.

He aquí un ejemplo de todos modos.

@media(min-width:1200px){

    h1 {font-size:34px}

}
@media(min-width:992px){

    h1 {font-size:32px}

}
@media(min-width:768px){

    h1 {font-size:28px}

}
@media(max-width:767px){

    h1 {font-size:26px}

}

También tenga en cuenta que la ventana 480 se ha eliminado bootstrap 3.

 11
Author: Joshua Watson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-13 12:14:06

Utilizamos las siguientes consultas de medios en nuestros archivos Less para crear los puntos de interrupción clave en nuestro sistema de cuadrícula.

/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) { ... }

/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) { ... }

/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) { ... }

Ver también en Bootstrap

 5
Author: csehasib,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-24 12:55:02

Puede ver en mi ejemplo que los tamaños de fuente y los colores de fondo están cambiando de acuerdo con el tamaño de la pantalla

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
    background-color: lightgreen;
}
/* Custom, iPhone Retina */ 
@media(max-width:320px){
    body {
        background-color: lime;
        font-size:14px;
     }
}
@media only screen and (min-width : 320px) {
     body {
        background-color: red;
        font-size:18px;
    }
}
/* Extra Small Devices, Phones */ 
@media only screen and (min-width : 480px) {
     body {
        background-color: aqua;
        font-size:24px;
    }
}
/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {
     body {
        background-color: green;
        font-size:30px;
    }
}
/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {
     body {
        background-color: grey;
        font-size:34px;
    }
}
/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {
     body {
        background-color: black;
        font-size:42px;
    }
}
</style>
</head>
<body>
<p>Resize the browser window. When the width of this document is larger than the height, the background-color is "lightblue", otherwise it is "lightgreen".</p>
</body>
</html>
 4
Author: Ganesh Putta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-20 10:06:21

Aquí hay una solución integral aún más fácil, que incluye archivos responsivos separados basados en consultas de medios.

Esto permite que toda la lógica de consulta de medios y la lógica de inclusión solo tengan que existir en una página, el cargador. También permite que las consultas de medios no desordenen las hojas de estilo receptivas.

//loader.less

// this twbs include adds all bs functionality, including added libraries such as elements.less, and our custom variables
@import '/app/Resources/less/bootstrap.less';

/*
* Our base custom twbs overrides
* (phones, xs, i.e. less than 768px, and up)
* no media query needed for this one since this is the default in Bootstrap
* All styles initially go here.  When you need a larger screen override, move those     
* overrides to one of the responsive files below
*/
@import 'base.less';

/*
* Our responsive overrides based on our breakpoint vars
*/
@import url("sm-min.less") (min-width: @screen-sm-min); //(tablets, 768px and up)
@import url("md-min.less") (min-width: @screen-md-min); //(desktops, 992px and up)
@import url("large-min.less") (min-width: @screen-lg-min); //(large desktops, 1200px and up)

Base.menos se vería así

/**
* base.less
* bootstrap overrides
* Extra small devices, phones, less than 768px, and up
* No media query since this is the default in Bootstrap
* all master site styles go here
* place any responsive overrides in the perspective responsive sheets themselves
*/
body{
  background-color: @fadedblue;
}

Sm-min.menos se vería así

/**
* sm-min.less
* min-width: @screen-sm-min
* Small devices (tablets, 768px and up)
*/
body{
  background-color: @fadedgreen;
}

Su índice solo tendría que cargar el cargador.menos

<link rel="stylesheet/less" type="text/css" href="loader.less" />

Pan comido..

 2
Author: blamb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-02 00:42:10

@media solo pantalla y (max-width : 1200px) {}

@media solo pantalla y (max-width : 979px) {}

@media solo pantalla y (max-width : 767px) {}

@media solo pantalla y (max-width : 480px) {}

@media solo pantalla y (max-width : 320px) {}

@media (min-width: 768px) y (max-width: 991px) {}

@media (min-width: 992px) y (max-width: 1024px) {}

 1
Author: Ashu Designer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-10 12:03:04

Use media queries para IE;

@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) 
and (orientation : landscape) and (-ms-high-contrast: none), (-ms-high-contrast: active) {
}
@media only screen 
and (min-device-width : 360px) 
and (max-device-width : 640px) 
and (orientation : portrait) and (-ms-high-contrast: none), (-ms-high-contrast: active) {
}
 0
Author: Apps Tawale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-25 16:06:18