What is the best way to center a parent container vertically?

I currently have a main grid with grid items that are also containers, set as inline-sized containers to allow for different internal layouts based on their width.

How can I horizontally align the main grid in the center once it exceeds a certain width? Attempts using justify-self: center and margin: 0 auto on the main grid result in layout issues - these can easily be observed by uncommenting those lines in the code below. The same issue arises when trying justify-content: center on either the main grid or the body element.

To see the current behavior above the max-width set for the main grid in action, expand the snippet below and resize the viewport: the grid stays left-aligned instead of being horizontally centered. My goal is to keep it positioned in the middle while preventing the layout from collapsing.

Answer №1

After receiving a suggestion from @deEr to adjust the main element's width, an idea struck me. In order for main to remain flexible up to a certain point, it could be assigned a max-width value to limit its growth.

However, an alternative approach would be to use width: min(100%, 800px) instead of setting a max-width. By including box-sizing: border-box to prevent overflow due to padding, suddenly all my previous unsuccessful attempts started working!

This simple adjustment was the key to unlocking the functionality I had been struggling with. It goes to show that sometimes, thinking outside the box can lead to unexpected solutions.

Answer №2

Using width: 100% is another option

addEventListener('input', e => {
    document.body.style = `--${e.target.id}: 1`
})
/* basic reset, grid everything */
* { margin: 0; padding: 0 }
html,body, main, section, div, ul, figure { display: grid }
html { min-height: 100% }

body {
    /* body stle may override these two; 
     * they're mutually exclusive */
    /* 1 if images are _N_ext to each other, 0 otherwise */
    --_n: var(--n, 0);
    /* 1 if images are _S_tacked, 0 otherwise */
    --_s: var(--s, 0);
    
    font: clamp(.75em, 3.375vw, 1.25em)/ 1.25 sans-serif;
}

main {
    grid-gap: .5em;
    place-self: center;
    padding: .5em;
    max-width: 800px;
    Using width: 100%;
    box-sizing: border-box;
}

/* CSS variable indices for similar items */
:is(input, label, li, figure):nth-of-type(1) { --i: 0 }
:is(input, label, li, figure):nth-of-type(2) { --i: 1 }
:is(input, label, li, figure):nth-of-type(3) { --i: 2 }
:is(input, label, li, figure):nth-of-type(4) { --i: 3 }

.ctr {
    grid-gap: inherit;
    padding: inherit;
    background: gainsboro;
}

div { grid-gap: inherit }

.one, .two, .res {
    container-type: inline-size;
    
    * {
        /* a bunch of container size cases */
        --_cs0: var(--cs0, 1);
        --_cs1: var(--cs1, calc(1 - var(--_cs0)));
        --_cs2: var(--cs2, calc(1 - (var(--_cs0) + var(--_cs1))));
    }
}

/* SECTION 1 */
.boo, .foo {
    @container (min-width: 23em) { --cs0: 0 }
    @container (min-width: 32em) { --cs1: 0 }
}

.boo {
    grid-column: calc(2 - var(--_cs1))/ span calc(1 + var(--_cs1))
}

li {
    grid-column: calc(1 + var(--_cs1)*var(--i))
}

.foo {
    grid-area: calc(1 + var(--_cs1))/ 1;
    grid-template-columns: repeat(2, max-content)
}

.xtra {
    overflow: hidden;
    width: calc((1 - var(--_cs0))*9em)
}


/* SECTION 2 */
[name='c'], [for] {
    grid-area: 
        calc(1 + var(--i)*var(--_cs0))/ 
        calc(1 + var(--i)*var(--_cs1));
    
    @container (min-width: 20em) { --cs0: 0 }
}



/* SECTION 4 */
figure {
    grid-area: calc(1 + var(--_cs0)*var(--i)*var(--_n))/ 
        calc(1 + var(--_cs1)*var(--i)*var(--_n));
    max-width: 400px;
    aspect-ratio: 2/ calc(2 + var(--_s) + var(--_cs1)*var(--_n));
    
    @container (min-width: 20em) { --cs0: 0  }
}

img {
    Using width: 100%; height: 100%;
    object-fit: cover;
    object-position: var(--pos)
}
<body style="--n: 1">
  <main>
    <section class="ctr one">
      <ul class="boo">
        <li>listitem</li>
        <li>listitem</li>
          <li>listitem</li>
        <li>listitem</li>
      </ul>
      <div class="foo">
        <div class="xtra">superfluous</div>
        <div class="main">
          <div>some</div>
          <div>essential</div>
          <div>shit</div>
          <div>keep it!</div>
        </div>
      </div>
    </section>
    <section class="ctr two">
      <input id="n" type="radio" name="c" checked="checked"/>
      <label for="n">side by side</label>
      <input id="s" type="radio" name="c"/>
      <label for="s">stacked</label>
    </section>
    <section class="ctr tre">
      <div>more stuff</div>
    </section>
    <section class="res">
      <figure><img src="https://images.unsplash.com/photo-1705630547844-29adf8323f28?w=800"/></figure>
      <figure><img src="https://images.unsplash.com/photo-1705630547844-29adf8323f28?w=800"/></figure>
    </section>
  </main>
</body>

Answer №3

A more effective way to center the main tag in CSS is to use only the width property instead of max-width, and employ the view-port unit (vw) for responsiveness. You can then apply the justify-self property in your CSS.

Here's the corrected CSS:

main {
    grid-gap: .5em;
    padding: .5em;
    justify-self: center;
    max-width: 800px;
    width: 80vw;
}

This approach will help you properly center the main section.

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

I'm having trouble getting my button to float correctly on the right side

Here I am facing a unique situation where I am attempting to align my button input[type="submit"] to the right side. I have allocated space for it and therefore trying to float the button to the right so that it can be positioned next to my input text. U ...

The HTML element update event was not triggered due to the excessive load of a JavaScript function

I am currently running a JavaScript function that is quite CPU intensive. To provide visual feedback to users when it starts and stops, I am attempting to display a badge on the webpage. Below is the code snippet: function updateView() { console.log(1 ...

In order to position content at the center of a <div> element

Just recently delving into the world of Bootstrap, I've hit a roadblock. Here's my current conundrum: <div class="container px-4 py-5" id="hanging-icons"> <h2 class="pb-2 border-bottom">Work Experie ...

Ways to display distinct text boxes based on selected radio button?

Currently, I am working with JSP and have implemented an HTML form that includes a "Process" button at the top. When this button is clicked, it displays a form with two radio buttons - TestClient and TestServer. The form also contains a Submit button. If ...

I can't figure out why my unslider isn't adapting to the screen size. Check out the fiddle for more details

I recently implemented unslider to create a slideshow that spans 100% of the width on my website. Everything seemed to be working fine until I tried resizing the screen, and the slides remained the same size as they were initially loaded. Here is the code ...

What causes Next.JS to automatically strip out CSS during the production build process?

Encountering unpredictability in CSS loading while deploying my Next.JS site. Everything appears fine locally, but once deployed, the CSS rules seem to vanish entirely. The element has the attached class, yet the corresponding styling rules are nowhere to ...

How can I achieve a transparent background for a radio button in Chrome?

Today, I spent some time experimenting with the radio button to see if I could make its background transparent. I attempted the following CSS styling: input[type=radio] { background-color:transparent; background-image:none; -webkit-backface-v ...

Integrate an input field with a copy function similar to the GitHub clone view

Can anyone help me create a view with a tooltip similar to the one on Github? You can see the example here: https://i.sstatic.net/iBSof.png I attempted to use CSS but couldn't quite replicate the exact UI. Here is my current CSS code: [tooltip] { ...

Buttons are misaligned and do not align on a straight line

Below is the code output: https://i.stack.imgur.com/avhUu.png I am attempting to enhance the symmetry of these buttons. The minus (-) button appears slightly smaller than the plus (+) button even though they have the same padding. I have experimented w ...

Choosing between JavaScript and Handlebars.js depends on the specific needs

Can anyone explain the advantages of utilizing Handlebars.js or similar libraries over solely relying on JavaScript? Thus far, I haven't come across any functionality in Handlebars that cannot be achieved with just pure JavaScript. ...

How deep can nesting go within a CSS rule?

When working with stylesheets, the majority of CSS rules follow a structured format: selector { property_1 : value_1; . . . property_n : value_n; } Each selector typically has only one {} block attached to it (without any sub {} blocks ...

How can I transform an HTML element into a textarea using CSS or JavaScript?

While browsing a webpage, I discovered a <div> element with the class .plainMail and I want to find a way to easily select all its text by simply pressing Ctrl+A. Currently using Firefox 22, I am considering converting the div.plainMail into a texta ...

The MUI snackbar element lingers in the DOM even after it has been closed

Having created a global modal with the intention of only utilizing it when necessary, I've encountered an issue where the snackbar div persists in the DOM. This persistence is causing certain elements to become blocked as they appear beneath this div. ...

Is there a way to relocate the play again button below the box?

How can I ensure that my "Play Again" button moves up to align perfectly under the black border box? The black border box is styled with a class named .foot .button { background: rgb(247, 150, 192); background: radial-gradient(circle, rgba(247, 1 ...

The CSS list formatting does not seem to be compatible with Bootstrap 4

For my website, I am working on creating a table using the list method along with CSS. However, I encountered a problem where the table is not displaying correctly when Bootstrap CDN is applied. Removing Bootstrap CDN resolves the issue, but I need to keep ...

Use PHP to highlight the row that has been selected in an HTML table

I am currently working on a project where I have styled multiple HTML tables on my website using alternating gray and white bands. Now, my goal is to highlight the selected row in a darker shade of gray. I have experimented with various solutions, and the ...

Are there any class options that offer a wider width than modal-lg?

I am currently using vue.js along with Bootstrap. Within my modal dive, I am looking for a class that will help me increase the width of the modal div, As you can see from the image below, my modal div looks like this. I plan on adding 12 more tabs, whic ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

Image displayed in tooltip when hovering over

I have been experimenting with displaying an image in a tooltip when hovering over it. I came across a fantastic solution that suits my needs: Codepen CSS: @import "compass"; * { box-sizing: border-box; } .tooltip { position: relative; border-bo ...

How to toggle elements using CSS slide animations?

Is there a way to make a div slide in and out from the left to right when the user clicks on "clickthis"? Here is an example of CSS code: .container{width:100px; position:absolute; left:-70px;} .container .open{left:0px;} .button{display:block; top:0px; ...