CSS for Web Development

0% completed

Previous
Next
Media Queries

Media queries let you apply CSS rules based on the device or viewport properties. With media queries, you can change styles depending on screen size, resolution, or orientation. This allows your site to respond to different devices, making your design flexible and user-friendly.

Syntax

Follow the code block below to set up media queries in CSS:

@media (condition) { /* CSS rules go here */ } /* Example conditions: @media (min-width: 600px) { ... } @media (max-width: 500px) { ... } @media (orientation: portrait) { ... } */

Explanation:

  • @media (condition):
    • This block applies the enclosed CSS only when the condition is met.
  • min-width / max-width:
    • Conditions that check if the viewport is at or above a minimum width, or at or below a maximum width.
  • orientation:
    • Checks if the device is in portrait or landscape mode.

Example 1: Adjusting Layout for Small Screens

In this example, we use a media query to change the background color and font size when the viewport width is 500px or less.

HTML

. . . .

Explanation:

  • Default Styles:
    • The base styles set the font size to 18px and the background color to light gray.
  • Media Query Condition:
    • When the viewport is 500px wide or less, the media query applies, reducing the font size to 16px and changing the background color.
  • Outcome:
    • The page adjusts for smaller screens, improving readability and appearance.

Example 2: Changing Layout Based on Orientation

In this example, we use a media query to modify layout when the device is in landscape mode. The container changes from a single column to two columns when in landscape orientation.

HTML

. . . .

Explanation:

  • Default Layout:
    • The container displays grid items in a single column by default.
  • Media Query for Orientation:
    • When the device is in landscape mode, the grid switches to a two-column layout.
  • Outcome:
    • The layout adapts to the device’s orientation, making the most of the available screen space.

Media queries are vital for responsive design. They let you adjust styles based on screen size, orientation, and other conditions. With media queries, you can create websites that look and work well on any device, ensuring that users have a smooth and effective experience.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next