CSS - Responsive Design

1. What is Responsive Design?

Responsive Design is a technique used in web development to make websites adapt to different screen sizes and devices (mobile, tablet, desktop). It ensures a good user experience across all devices by adjusting layout and content dynamically.

2. Media Queries in CSS

Media queries allow you to apply different CSS styles depending on the device's screen size, resolution, or other features.

Example: Changing Background Color Based on Screen Width

<div class="responsive-box">Resize the screen to see color change</div>

<style>
.responsive-box {
  padding: 20px;
  color: white;
  text-align: center;
  background-color: blue;
}
				@media (max-width: 768px) {
  .responsive-box {
	background-color: green;
  }
}
				@media (max-width: 480px) {
  .responsive-box {
	background-color: red;
  }
}
</style>
Resize the screen to see color change

3. Mobile-first Design

Mobile-first design means writing CSS for small screens first and adding styles for larger screens using media queries. This approach ensures your content works on mobile devices from the start.

Example: Mobile-first Responsive Layout

<div class="container">
  <div class="box">Box 1</div>
  <div class="box">Box 2</div>
</div>

<style>
.container {
  display: block;
}
.box {
  background: #007BFF;
  color: white;
  padding: 20px;
  margin: 10px 0;
}
				@media (min-width: 600px) {
  .container {
	display: flex;
	gap: 10px;
  }
  .box {
	flex: 1;
	margin: 0;
  }
}
</style>
Box 1
Box 2

4. Units in CSS

CSS supports different units for sizing and spacing elements. Some are fixed, while others are relative to screen or font size:

  • px – Pixels (fixed size)
  • em – Relative to the font-size of the parent
  • rem – Relative to the root font-size
  • % – Relative to the parent element
  • vh – 1% of viewport height
  • vw – 1% of viewport width

Example: Using Various Units

<div style="width: 80%; height: 10vh; background: #333; color: white; font-size: 2rem; padding: 1em;">
  Responsive Box with Various Units
</div>
Responsive Box with Various Units

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!