Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Building Responsive Layouts | Forms and Final Project
Introduction to Svelte

Building Responsive Layouts

Swipe to show menu

Modern applications should work well on different screen sizes. A layout that looks good on a laptop may feel cramped on a phone, so frontend developers need to build interfaces that adapt naturally.

In this chapter, you will create responsive layouts in Svelte using regular CSS.

What Responsive Layouts Are

A responsive layout changes depending on the available screen size. Instead of designing only for one device, developers create interfaces that can adjust for phones, tablets, and desktop screens.

This usually involves flexible widths, spacing, wrapping content, and changing layout direction when the screen becomes smaller.

Creating a Flexible Layout

Add this structure inside a Svelte component:

<div class="layout">
  <section class="content">
    <h2>Main Content</h2>
    <p>This section takes more space on larger screens.</p>
  </section>

  <aside class="sidebar">
    <h3>Sidebar</h3>
    <p>This section moves below the content on smaller screens.</p>
  </aside>
</div>

Then add the styles:

<style>
  .layout {
    display: flex;
    gap: 24px;
  }

  .content {
    flex: 2;
  }

  .sidebar {
    flex: 1;
  }
</style>

This creates a simple two-column layout.

Adding a Media Query

A media query allows CSS to apply different styles at different screen sizes.

<style>
  .layout {
    display: flex;
    gap: 24px;
  }

  .content {
    flex: 2;
  }

  .sidebar {
    flex: 1;
  }

  @media (max-width: 768px) {
    .layout {
      flex-direction: column;
    }
  }
</style>

When the screen becomes smaller, the layout changes from two columns to a single column.

Responsive Layouts in Svelte

Svelte does not require a special syntax for responsive design. You can write normal CSS inside the component's <style> block, and the styles remain scoped to that component.

This makes it easy to build responsive components without affecting the rest of the application.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 7. Chapter 5

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 7. Chapter 5
some-alt