Technology Encyclopedia Home >How to set up responsive layout with CSS?

How to set up responsive layout with CSS?

To set up a responsive layout with CSS, you can use several techniques, primarily involving media queries, flexible grids, and flexible images. Here's a brief explanation along with an example:

Media Queries

Media queries allow you to apply different styles based on the characteristics of the device the website is being viewed on, such as screen width.

Example:

/* Default styles for all devices */
body {
  font-size: 16px;
}

/* Styles for screens smaller than 600px */
@media (max-width: 600px) {
  body {
    font-size: 14px;
  }
  .container {
    width: 100%;
  }
}

Flexible Grids

Using CSS frameworks like Bootstrap or creating your own grid system with CSS Flexbox or Grid layout helps in creating layouts that adjust based on the screen size.

Example using Flexbox:

.container {
  display: flex;
  flex-wrap: wrap;
}

.item {
  flex: 1 1 200px; /* Each item will be at least 200px wide and will grow and shrink as needed */
}

Flexible Images

Images should also be responsive to ensure they don't overflow their containers on smaller screens.

Example:

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

Example of a Simple Responsive Layout

Here’s a simple example combining the above techniques:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Responsive Layout</title>
  <style>
    .container {
      display: flex;
      flex-wrap: wrap;
    }
    .item {
      flex: 1 1 200px;
      padding: 10px;
      box-sizing: border-box;
    }
    img {
      max-width: 100%;
      height: auto;
    }
    @media (max-width: 600px) {
      .item {
        flex: 1 1 100%;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="item"><img src="image1.jpg" alt="Image 1"></div>
    <div class="item"><img src="image2.jpg" alt="Image 2"></div>
    <div class="item"><img src="image3.jpg" alt="Image 3"></div>
  </div>
</body>
</html>

Cloud Services Recommendation

For hosting and deploying your responsive website, consider using Tencent Cloud's services. For instance, you can use Tencent Cloud CDN to ensure your website loads quickly across different geographic locations, and Tencent Cloud Hosting for reliable web hosting services.