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:
🔍 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:
🔄 Bonus: Need to Detect Screen Width Dynamically?
If you want to get the screen width dynamically, you’ll need JavaScript, like so:
But for purely styling based on screen size, CSS media queries are the correct tool.
📌 Summary: How to Get Screen Width in CSS
-
✅ Use
@mediaqueries 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
