Utilizing CSS to maintain the layout of content in portrait or square orientation

Is there an optimal approach to ensure that a webpage's square content appears "tall" when viewed in different screen orientations? For instance, when the device is held vertically, the content should occupy the full width, whereas in horizontal orientation, sidebars would appear on either side of the content, resulting in a square layout filling the entire height.

I have currently implemented this functionality using JavaScript, by monitoring the resize event, examining the container's dimensions, and manually computing widths and margins. However, I am curious if there is a more efficient method, possibly utilizing a pure CSS3 solution.

After reviewing Google's responsive guide, my assumption is that a custom stylesheet might be able to achieve this outcome, but I am uncertain on how to consistently fill the content in either the height or width direction.

To illustrate, here are examples of what the design would look like in portrait and landscape modes, with the red area representing the main content body, and the blue areas indicating additional space:

https://i.sstatic.net/JrkCB.png https://i.sstatic.net/MjYyX.png

I am presently exploring Angular Material, so if there is a framework-specific solution, that would also be satisfactory.

This is how the structure would be organized within the body - the Angular material grid tiles forming a 2x2 grid of equally sized squares, ensuring the overall body remains a square shape, without requiring scrolling:

<body>
    <!-- sidebar if needed -->
    <div id="left-side"></div>

    <div id="main-container">
        <mat-grid-list cols="2" rowHeight="1:1">
            <mat-grid-tile>First square</mat-grid-tile>
            <mat-grid-tile>Second square</mat-grid-tile>
            <mat-grid-tile>Third square</mat-grid-tile>
            <mat-grid-tile>Fourth square</mat-grid-tile>
        </mat-grid-list>
    </div>

    <!-- sidebar if needed -->
    <div id="right-side"></div>
</body>

Answer №1

Here is a CSS code snippet that you can use:

body {
  margin: 0;
  background-color: blue;
}
#wrapper {
  margin: 0 auto;
  max-width: 100vh;
  background-color: red;
}
<div id="wrapper">Content</div>

When the device is in portrait mode, the wrapper will have a width of 100%, and in landscape mode, the wrapper's width will match the screen height.

For reference, here is an example that aligns with the screenshots provided:

body {
  margin: 0;
  background-color: blue;
}
#wrapper {
  margin: 0 auto;
  max-width: 100vh;
  background-color: red;
}
/* For landscape mode: wrapper takes full height */
@media screen and (orientation: landscape) {
  #wrapper {
    min-height: 100vh;
  }
}
/* For portrait mode: wrapper has same height as width */
@media screen and (orientation: portrait) {
  #wrapper {
    min-height: 100vw;
  }
}
<div id="wrapper">Content</div>

Answer №2

To achieve a similar layout, you can leverage the CSS grid defaults along with the vh unit. By creating a 2x2 grid and setting the children to have a height of 50vh, you can center the grid container.

The use of vh allows for dynamic sizing based on viewport height, while display:grid handles horizontal positioning, making the layout responsive automatically.

(Note: I included a max-width on the container and a tall height on <main> for demonstration purposes, but these are not strictly necessary).

HTML:

<main>
  <section class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </section>
</main>

CSS:

main {
  height: 500vh;
}

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  margin: 0 auto;
  max-width: 800px;
  width: 100%;
}

.item {
  background-color: lightblue;
  border: 1px solid black;
  height: 50vh;
}

Demo: https://codepen.io/staypuftman/pen/JZwvMQ

Answer №3

Is this the kind of thing you're looking for?

body {
  margin: 0;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  background: blue;
}

mat\-grid\-list {
  display: grid;
  grid: repeat(2, 1fr)/repeat(2, 1fr);
  width: 100vmin;
  height: 100vmin;
  background: red;
  grid-gap: 2px;
}

mat\-grid\-tile {
  border: 1px solid #888;
}
<body>
    <div id="main-container">
        <mat-grid-list cols="2" rowHeight="1:1">
            <mat-grid-tile>First square</mat-grid-tile>
            <mat-grid-tile>Second square</mat-grid-tile>
            <mat-grid-tile>Third square</mat-grid-tile>
            <mat-grid-tile>Fourth square</mat-grid-tile>
        </mat-grid-list>
    </div>
</body>

Answer №4

By utilizing the aspect-ratio property, you can eliminate the need for media queries as suggested in @Salman A's response. This feature was not widely accessible when the query was initially posed, but it now boasts strong support.

body {
      margin: 0;
      background-color: blue;
    }
#wrapper {
  margin: 0 auto;
  max-width: 100vh;
  aspect-ratio: 1/1;
  background-color: red;
}
<div id="wrapper">Content</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue arises when the mat-panel-description is not properly aligned with the shrinking panel

Within my HTML, I have a mat-panel with a description that is populated by a variable from the TS file. However, I am encountering an issue where if I shrink the panel and the description is too long, the text is cut off at the top and bottom. Is there a w ...

Struggling with the alignment of pictures inside a container

I utilized the Instafeed.js library to fetch the three most recent images from an Instagram account. These images are loaded into a specific div and I successfully customized their styling according to my requirements. However, the current setup is quite s ...

Navigating Through the DOM with Selenium using XPath Axes

Currently, I am developing Selenium tests for a dynamic web page. Within this section of code, I am extracting data from an Excel sheet and verifying if a specific element exists on the webpage. I have annotated the critical part of the code with comments ...

Full-width sub menu within the menu

I'm trying to make a sub menu appear below my main menu that is the same width as the main menu, which has a fixed width. I want the sub menu to adjust its width based on the number of links it contains. Is this even possible? Here's the code I h ...

Transform a binary large object (BLOB) file, specifically a music file, into a .WAV format using NODE.js on the server

I'm having difficulty grasping a basic concept. My Node server is successfully handling POST requests. I am sending a Blob to it (converting the blob to a .wav file). How can I save this Blob as a .wav file on disk? I want to use a music player to ...

Is there a way to position my character at the exact center of my mouse click coordinates instead of the top left corner?

In my game, players can click on a 2D HTML5 canvas to set a point for their character to move to. However, I've noticed that when I click, the character appears in the lower right corner of where my mouse is clicked. After some research, I realized th ...

What is the best way to create a dynamic component from scratch?

There's a captivating Animated Scrolling feature in the hero section of this particular website. I'm interested in learning how to recreate this component and implement it with tailwind CSS. Could you please check out the provided link for refere ...

Serving both HTML and JSON responses concurrently using PHP

Consider a scenario where a webpage contains elements generated in HTML directly from the server backend and others generated through JavaScript with data sourced from JSON. Upon initially loading the page, the HTML layout and its elements are delivered in ...

Is there a way to send me the result of the radio input (Yes/No) via email?

Is it feasible to send the results of a radio input (Yes/No) back to my email directly using HTML, CSS, and Javascript? ...

What is the process for adding tailwind CSS via npm?

Before, I was including Tailwind using a CDN. Now, I have installed it with npm and all three .css files are included, but the styles are not appearing in my HTML document. Here is the directory structure and a link to style.css The content of tailwind.c ...

What is the most effective way to showcase a variety of random styles for various text elements within a single webpage?

Currently brainstorming some new concepts and contemplating a unique site layout idea that involves randomizing the styles of specific elements on a webpage. For instance, envision having 10 paragraphs on one page where each paragraph is presented in a dif ...

What is causing the Jquery form submit event to not trigger?

I am attempting to use jQuery to submit a form. I need the form submit event to be triggered when jQuery submits the form. However, the submit event handler is not being called successfully after the form is submitted. Here is the code snippet: <html ...

Implement a download feature into Django's change view

I have successfully included a button next to the save buttons in my django change view: {% extends 'admin/change_form.html' %} {% load static %} {% load i18n %} {% block submit_buttons_bottom %} <div class="submit-row"> ...

Issue with footer not properly aligning on the page's bottom

In my current project, I am utilizing both angularjs and node js for development. Within my index.html, the views are being called in the following manner: <div ng-include="'views/header/header.view.html'"></div> <div ng-view styl ...

Using the jQuery validation plugin to pass a function as a parameter

Currently, I am in the process of developing a jQuery plugin that can effectively validate forms. Although the plugin functions well overall, I am eager to implement a feature that allows for specifying actions following successful validation. This entails ...

Ensure that the table is padded while keeping the cells collapsed

I am currently working on creating a table with borders between each row. However, I am facing an issue where the row borders are touching the outer border of the table. Despite my efforts, I have been unable to find a solution to this problem. I feel like ...

Connecting your HTML file to a CSS stylesheet

I'm struggling to connect my "index.html" file with my "stylesheet.css" file. I've tried copying the code from resources like CodeAcademy and w3schools, but nothing seems to be working. I'm currently using Notepad++ as my text editor - could ...

Issues with JavaScript scripts functionality on my live server

Hey everyone, I'm new to this community and having some trouble with my index.html file. Everything works fine except for one script that only runs when I open the file directly with live server in VSCode. Can someone help me out? The script causing i ...

Impossible to create margins on both the left and right side

Check out this cool pen: http://codepen.io/helloworld/pen/BcjCJ?editors=110 I'm facing an issue where I'm unable to create both left and right margins around my datagrid. Only the left margin seems to be possible. Any suggestions on how I can f ...

Node.js: My webpage needs an image to complete its look

During my training with Node and TypeScript, I attempted to create a simple server with multiple request/response options. However, I encountered a problem that I am struggling to solve without using Express (at least for now). I have an HTML file that re ...