If you’re asking, “How to get screen width in CSS?”, you’re likely trying to build a responsive website that adapts to different screen sizes. While CSS can’t “get” screen width like JavaScript does, it reacts to screen size using a powerful feature called media queries.

In this quick guide, you’ll learn how to use CSS to target screen width, adapt styles for different devices, and create a smooth, responsive design.


🧠 Can CSS Get Screen Width?

CSS cannot retrieve screen width as a variable, but it can apply styles conditionally based on the screen’s width using @media queries. This is how responsive design works in modern web development.


✅ How to Use Media Queries to Target Screen Width

Here’s a basic example of how to apply CSS based on screen width:

css
/* Default styles for all screens */
body {
background-color: white;
font-size: 16px;
}

/* For screens narrower than 768px (e.g., tablets & phones) */
@media (max-width: 768px) {
body {
background-color: lightgray;
font-size: 14px;
}
}

/* For screens wider than 1200px (e.g., desktops) */
@media (min-width: 1200px) {
body {
max-width: 1140px;
margin: auto;
}
}

🔍 Common Media Query Breakpoints:

Device Type Screen Width Media Query Example
Mobile Phones 320px – 480px @media (max-width: 480px)
Tablets 481px – 768px @media (max-width: 768px)
Laptops/Desktops 769px – 1200px+ @media (min-width: 769px)

💡 Tip: Use Relative Units for Better Responsiveness

Using em, rem, %, or vw instead of fixed px units allows your styles to scale better across screen sizes.

Example:

css
.container {
width: 90vw; /* 90% of the viewport width */
}

🔄 Bonus: Need to Detect Screen Width Dynamically?

If you want to get the screen width dynamically, you’ll need JavaScript, like so:

javascript
console.log(window.innerWidth);

But for purely styling based on screen size, CSS media queries are the correct tool.


📌 Summary: How to Get Screen Width in CSS

  • ✅ Use @media queries to apply CSS based on screen width

  • 🎯 Ideal for responsive layouts

  • ❌ CSS doesn’t retrieve values like JavaScript, but it adapts based on viewport size

  • 🧩 Combine with flexible layouts and relative units for best results

Sign In

Sign Up