October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Change a Webpage Layout on Click with HTML, CSS, and JavaScript

Use one wrapper state class to switch named layouts on click. For responsive previews, change an iframe’s width so the page’s media queries can run at that viewport.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To change a webpage’s layout when someone clicks a button, keep the same HTML and use JavaScript to toggle a CSS class on a wrapper element. CSS then applies the selected arrangement. If you mean a live mobile or desktop preview, use an iframe at the desired width instead: a layout class alone does not make the browser recalculate responsive breakpoints.

Change the page layout with a button

For named layouts such as “wide” and “compact,” put the page content inside one wrapper and use a click handler to change its state. This keeps layout rules in CSS rather than scattering style changes throughout JavaScript.

<button type="button" id="layout-toggle" aria-pressed="false">Change layout</button>
<section id="page" class="layout-wide">
  <article class="card">Main content</article>
  <aside class="sidebar">Sidebar</aside>
</section>
.layout-wide {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 1rem;
}

.layout-compact {
  display: block;
}

.layout-compact .sidebar {
  margin-top: 1rem;
}
const button = document.querySelector('#layout-toggle');
const page = document.querySelector('#page');

button.addEventListener('click', () => {
  const compact = page.classList.toggle('layout-compact');
  page.classList.toggle('layout-wide', !compact);
  button.setAttribute('aria-pressed', String(compact));
});

The wrapper class is the layout state: descendant selectors can coordinate the main content, sidebar, spacing, and other components. The button’s aria-pressed value announces whether the toggle is on to assistive technology. If you offer three or more named layouts, use a labeled radio group rather than presenting a multi-option choice as one on/off toggle.

Choose the right approach for the behavior you want

Goal Use What changes
Switch a product UI between named arrangements A state class on the page wrapper or body The live page’s CSS layout changes; media-query behavior does not change unless the viewport changes.
Preview how a page responds at phone, tablet, or desktop widths An iframe with a controlled width The page inside the frame gets a different viewport width, so its media queries can respond.
Maintain genuinely separate style systems Switch stylesheets when a layout is selected The selected stylesheet supplies the alternative styling; this is usually unnecessary for a small number of layout differences.
Inspect a page at another viewport size while developing Browser developer tools’ device emulation The browser displays the page at an emulated viewport without adding a preview control to the site.

A SitePoint Forums discussion recommends using CSS for layout and switching the stylesheet selected by the user when the layouts are distinct style systems: On click: change layout with HTML and CSS. For ordinary variations, a wrapper state class is simpler to keep consistent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For responsive previews, change the preview viewport

Responsive CSS depends on the width of the viewport, not on whether a “mobile” class has been added to an element. To build a visual editor with phone and desktop preview buttons, place the page in an iframe and change the iframe’s width. Presets such as 375px, 576px, 768px, 992px, and 1200px can represent useful preview sizes, but they are example widths—not a guarantee that every site uses those breakpoints.

Keep the editor controls outside the iframe. That way, changing the preview width affects the page being previewed rather than shrinking the controls used to operate the editor. If you only want to inspect your own page at a different size, device emulation in browser developer tools avoids building this feature into the site.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep the selected layout after a refresh

A class change exists only in the current page state, so the page returns to its default layout after a reload unless you save the selection. Store a small allowed value, such as compact, in localStorage, validate it when restoring, and update the class and button state together.

const button = document.querySelector('#layout-toggle');
const page = document.querySelector('#page');
const allowedLayouts = new Set(['wide', 'compact']);

function setLayout(layout) {
  if (!allowedLayouts.has(layout)) return;

  page.classList.toggle('layout-wide', layout === 'wide');
  page.classList.toggle('layout-compact', layout === 'compact');
  button.setAttribute('aria-pressed', String(layout === 'compact'));
}

const savedLayout = localStorage.getItem('layout');
setLayout(allowedLayouts.has(savedLayout) ? savedLayout : 'wide');

button.addEventListener('click', () => {
  const nextLayout = page.classList.contains('layout-compact') ? 'wide' : 'compact';
  setLayout(nextLayout);
  localStorage.setItem('layout', nextLayout);
});

This example treats the button as a two-state wide/compact toggle. When using more layouts, give users a labeled choice for each and persist only values your interface supports.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

SaleBestseller No. 2
HTML and CSS: Design and Build Websites
HTML and CSS: Design and Build Websites
HTML CSS Design and Build Web Sites; Comes with secure packaging; It can be a gift option
$14.94
SaleBestseller No. 4
Web Design with HTML, CSS, JavaScript and jQuery Set
Web Design with HTML, CSS, JavaScript and jQuery Set
Brand: Wiley; Set of 2 Volumes
$35.05
Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers

Common mistakes to avoid

  • Toggling only one column: If several components must change together, toggle one parent state and write descendant CSS rules for the coordinated layout.
  • Using a class as a substitute for viewport testing: A class can restyle an element, but it does not make media queries behave as if the browser window were narrower.
  • Leaving the control’s state unclear: Keep aria-pressed in sync with the active layout, or use labeled radio buttons for multiple alternatives.
  • Trusting saved data without checking it: Accept only known layout names when reading from localStorage; if the stored value is absent or invalid, apply the default.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.