Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
How to add CSS in HTML
Types of CSS Files
Flex in CSS
Media Query in CSS
CSS - background attribute
CSS - border
css - border-image
CSS align attributes
CSS color attribute
CSS cursor attribute
CSS display attribute
CSS font attributes
CSS height and max-height
CSS width and max-width
CSS padding attributes
CSS margin attributes
CSS mask attributes
CSS overflow attributes
CSS opacity attribute
CSS text decoration attributes
CSS visibility attribute
CSS word attributes
CSS z-index attribute

Media Query in CSS



In CSS, a media query is a technique used to apply different styles to different devices based on characteristics like screen size, resolution, orientation, and more. This helps make your web pages responsive, ensuring they look good on all devices, from mobile phones to large desktop monitors.

Basic Syntax

A media query is composed of a media type and one or more expressions that check for conditions of particular media features. Here's a simple example:

css
@media only screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

In this example:

  • @media is the media query keyword.

  • only screen specifies the media type (in this case, screen devices).

  • (max-width: 600px) is the media feature, which means this CSS will only apply if the viewport width is 600 pixels or less.

  • The CSS inside the {} brackets will apply when the conditions are met.

Common Media Features

Here are some commonly used media features:

  • width and height – The width and height of the viewport.

  • min-width and max-width – Minimum and maximum width of the viewport.

  • orientation – Checks if the device is in portrait or landscape mode.

  • resolution – Checks the resolution of the device in dots per inch (DPI) or dots per centimeter (DPCM).

Example

Here' a more comprehensive example:

css
/* Desktop styles */
body {
  background-color: white;
}

/* Tablet styles */
@media only screen and (min-width: 600px) and (max-width: 768px) {
  body {
    background-color: lightgreen;
  }
}

/* Mobile styles */
@media only screen and (max-width: 599px) {
  body {
    background-color: lightblue;
  }
}

In this example:

  • The default body background color is white.

  • For screens between 600px and 768px wide (typically tablets), the background color is light green.

  • For screens 599px wide or smaller (typically mobile devices), the background color is light blue.

Practical Use

Media queries are very useful when you want to ensure that your website provides an optimal viewing experience across a wide range of devices. By adjusting layout, typography, and other stylistic elements, you can make your content more accessible and enjoyable for all users.

Would you like to delve deeper into any specific aspect of media queries?




All rights reserved | Privacy Policy | Sitemap