HTML CSS - Media Queries
Using media queries for responsive design
Media queries are a powerful feature in CSS that allow you to apply styles based on specific conditions, such as screen width, height, resolution, and orientation. This tutorial covers how to use media queries for responsive design.
Key Points:
- Media queries help create responsive designs that adapt to different devices and screen sizes.
- You can apply CSS rules based on conditions such as screen width, height, orientation, and resolution.
- Commonly used for adjusting layouts, fonts, images, and other design elements.
Basic Media Query Syntax
The basic syntax of a media query includes the @media
rule followed by a condition and a block of CSS rules. Here is an example:
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
Applying Media Queries
Media queries can be used to apply different styles based on screen width, height, orientation, and resolution. Here are some common examples:
Screen Width
Applying styles based on screen width:
/* Styles for devices with a maximum width of 600px */
@media (max-width: 600px) {
.container {
padding: 5px;
}
}
/* Styles for devices with a minimum width of 601px */
@media (min-width: 601px) {
.container {
padding: 20px;
}
}
Screen Height
Applying styles based on screen height:
/* Styles for devices with a maximum height of 800px */
@media (max-height: 800px) {
.header {
height: 50px;
}
}
Orientation
Applying styles based on screen orientation:
/* Styles for devices in landscape orientation */
@media (orientation: landscape) {
.sidebar {
display: none;
}
}
Resolution
Applying styles based on screen resolution:
/* Styles for devices with a resolution of at least 2dppx */
@media (min-resolution: 2dppx) {
.image {
background-image: url('high-res-image.png');
}
}
Combining Media Queries
You can combine multiple conditions in a single media query using logical operators such as and
, or
, and not
. Here is an example:
/* Styles for devices with a screen width between 600px and 900px */
@media (min-width: 600px) and (max-width: 900px) {
.content {
font-size: 18px;
}
}
Media Queries for Different Devices
Here are some common media queries for different devices:
Mobile Devices
/* Styles for mobile devices */
@media (max-width: 600px) {
.nav {
display: none;
}
}
Tablets
/* Styles for tablets */
@media (min-width: 601px) and (max-width: 900px) {
.sidebar {
width: 200px;
}
}
Desktops
/* Styles for desktops */
@media (min-width: 901px) {
.content {
max-width: 1200px;
margin: auto;
}
}
Summary
In this tutorial, you learned about using media queries for responsive design. Media queries allow you to apply CSS rules based on specific conditions, such as screen width, height, orientation, and resolution. Understanding and using media queries is essential for creating responsive web designs that adapt to different devices and screen sizes.