CSS Responsive Layout

Responsive Images

Basic Responsive Image

CSS
img {
  max-width: 100%;
  height: auto;
}

Responsive Background Image

CSS
.banner {
  background-image: url("desktop-bg.jpg");
  background-size: cover;
  background-position: center;
}

@media (max-width: 768px) {
  .banner {
    background-image: url("mobile-bg.jpg");
  }
}

Responsive Tables

Tables can overflow on small screens. Use overflow-x: auto for horizontal scrolling:

Example

HTML
<style>
.table-wrapper {
  overflow-x: auto;
}
table {
  width: 100%;
  border-collapse: collapse;
  min-width: 600px;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
</style>
<div class="table-wrapper">
  <table>
    <tr><th>Name</th><th>Email</th><th>Phone</th><th>Address</th><th>City</th></tr>
    <tr><td>John</td><td>john@email.com</td><td>123-456-7890</td><td>123 Main St</td><td>New York</td></tr>
  </table>
</div>
▶ Try it Yourself

Show/Hide Elements

Use media queries to show/hide elements at different breakpoints:

Example

HTML
<style>
.desktop-only {
  display: none;
}
.mobile-only {
  display: block;
}

@media (min-width: 768px) {
  .desktop-only {
    display: block;
  }
  .mobile-only {
    display: none;
  }
}
</style>
<div class="mobile-only">📱 Mobile only content</div>
<div class="desktop-only">🖥️ Desktop only content</div>
▶ Try it Yourself

Testing Responsive Layouts

  1. Browser resize: Drag browser window edges
  2. Chrome DevTools: F12 → Toggle device toolbar (Ctrl+Shift+M)
  3. Real devices: Test on actual phones/tablets when possible

❓ FAQ

Q How to make images responsive?
A Basic: `img { max-width: 100%; height: auto; }` ensures images don't overflow. Advanced: use `` and `` to load different resolutions at different screen sizes. Basic version is sufficient for most cases.
Q Must responsive design have three versions?
A No. Ensure mobile experience first, then enhance on larger screens. Many pages only need mobile + desktop versions; tablet is often a natural transition. Key is "content first, device adaptation" — not responsive for responsive's sake.
Q How to test responsive effects?
A Browser DevTools can simulate various device sizes, but testing on real devices is recommended. Touch interactions feel different from simulation. Online tools like responsinator.com can also help quick preview.

📖 Summary

📝 Exercises

  1. Create a "responsive personal blog" page with header navigation, article list, sidebar recommendations, and footer copyright. Requirements: mobile single column, tablet two columns, desktop three columns + fixed sidebar.
  2. Use min-width breakpoints to change a card grid from 1 column to 4 columns, observing at each breakpoint.
  3. Create a responsive table page where tables can scroll horizontally on small screens (using overflow-x: auto).
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏