- Home
- /
- CSS Media Queries Advanced
CSS Tutorial
Introduction
CSS Properties
CSS Designing
CSS Advance Topics
CSS FAQs
- Home
- /
- CSS Media Queries Advanced
CSS Media Queries (Advanced)
Media Queries play a vital role in making modern websites responsive. While we’ve touched on the basics CSS Media Queries earlier, let’s now take a deeper dive and explore how to build layouts that adjust smoothly across different screen sizes—from desktops to tablets to mobile phones.
What Are Media Queries?
Media queries allow you to apply CSS rules only when certain conditions are met, like the width of the screen, device type, or even orientation (landscape or portrait). Think of it like setting breakpoints for when your layout should adjust to the screen.
Basic Syntax:
@media media-type and (media-feature) {
/* Your CSS goes here */
}
@media
: Starts the media querymedia-type
: Defines the device type (e.g.,screen
,print
,all
)media-feature
: A condition like width, height, orientation, resolution, etc.
Let's Build a Responsive Box Layout
We’ll create a layout with 4 colored boxes. On large screens, they’ll appear in a row. On smaller screens (below 600px), they’ll stack vertically.
HTML
Responsive Boxes – Learn With Arshyan
Responsive Box Layout
Box 1
Box 2
Box 3
Box 4
CSS
body {
font-family: Arial, sans-serif;
padding: 20px;
text-align: center;
}
.box-container {
display: flex;
flex-direction: row;
justify-content: space-between;
flex-wrap: wrap;
gap: 10px;
}
.box {
flex: 1 1 22%;
padding: 40px 0;
color: white;
font-size: 18px;
border-radius: 6px;
}
.box1 { background-color: crimson; }
.box2 { background-color: seagreen; }
.box3 { background-color: dodgerblue; }
.box4 { background-color: goldenrod; }
/* Media Query: when screen width is 600px or less */
@media screen and (max-width: 600px) {
.box-container {
flex-direction: column;
align-items: center;
}
.box {
width: 80%;
font-size: 20px;
}
}
What Happens Here?
The
.box-container
usesflex-direction: row
for wider screens (default).Once the screen width drops below
600px
, the media query kicks in:The layout switches to
column
Boxes become centered and take up more width.
This is a simple but effective layout adjustment using only CSS.
When to Use Media Queries?
Use media queries when you need:
A different layout for mobile than desktop
Font sizes to adapt to screen size
Hiding or showing elements on specific devices
Changing grid or flex directions
Summary Table
Feature | Purpose |
---|---|
max-width | Triggers styles when screen is smaller than the given width |
min-width | Triggers styles when screen is larger than the given width |
orientation | Detects landscape or portrait mode |
screen type | Targets regular screens only |