Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Retrofit existing web page with mobile CSS
To retrofit an existing web page for mobile devices, use CSS media queries to apply different styles based on device characteristics. This approach requires no server-side code and automatically handles various device types.
Media queries allow you to target specific screen sizes, orientations, and device capabilities. They work by detecting browser and device properties, then applying appropriate CSS rules.
Basic Mobile Media Query
The most common approach targets screens with maximum widths for mobile devices:
@media screen and (max-width: 768px) {
body {
font-size: 16px;
padding: 10px;
}
.container {
width: 100%;
margin: 0;
}
}
Multi-Device Targeting
You can combine multiple conditions to target different device types and sizes:
@media handheld and (max-width: 480px),
screen and (max-device-width: 480px),
screen and (max-width: 600px) {
body {
color: blue;
font-size: 14px;
}
.navigation {
display: none;
}
.mobile-menu {
display: block;
}
}
Responsive Breakpoints
Use multiple media queries for different device categories:
/* Mobile phones */
@media screen and (max-width: 480px) {
.column {
width: 100%;
display: block;
}
}
/* Tablets */
@media screen and (min-width: 481px) and (max-width: 768px) {
.column {
width: 50%;
float: left;
}
}
/* Desktop */
@media screen and (min-width: 769px) {
.column {
width: 33.33%;
float: left;
}
}
Viewport Meta Tag
Always include the viewport meta tag in your HTML head for proper mobile rendering:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Key Benefits
| Advantage | Description |
|---|---|
| No Server Code | Pure CSS solution, no backend required |
| Automatic Detection | Handles unknown devices automatically |
| Performance | Loads appropriate styles only |
| SEO Friendly | Same URL for all devices |
Common Mobile Adjustments
@media screen and (max-width: 480px) {
/* Hide non-essential content */
.sidebar {
display: none;
}
/* Stack elements vertically */
.flex-container {
flex-direction: column;
}
/* Increase touch targets */
button, .link {
min-height: 44px;
padding: 12px;
}
/* Optimize text */
h1 {
font-size: 24px;
line-height: 1.2;
}
}
Conclusion
CSS media queries provide a powerful, client-side solution for mobile retrofitting. They automatically adapt to various devices without requiring server-side detection or multiple codebases, making maintenance simpler and performance better.
