CSS, Struggling to align element in the center due to varying sizes of its children

Greetings everyone! I wanted to share a snapshot of my current layout:

https://i.sstatic.net/Cl8x6.png

My grid consists of 3 rows and 3 columns, where each column is set to min-content, and the elements are centered within each cell. While it looks alright, I noticed that when the title expands significantly, the gap between the switch and categories becomes too large:

https://i.sstatic.net/0Fr1D.png

I attempted solving this by enclosing the middle row in a div container and using flex, but encountered alignment issues due to varying category sizes.

Even adjusting the category sizes resulted in misalignment when centering the entire component on the page, as the smaller category introduced unwanted white space pushing the component too far to the right.

Any suggestions on reducing this excess space while maintaining the switch perfectly centered between the title and button?

Below is the provided code:

The HTML:

<div class="category-switch">
  <div class="form-check category-switch__btn">
    <input class="form-check-input" type="checkbox" />
    <label class="form-check-label form-label">Disable</label>
  </div>
  <div class="category-switch__switch">
    <div class="switch">
      <div class="form-check">
        <input class="form-check-input" type="checkbox" />
        <label class="form-check-label form-label"></label>
      </div>
      <span class="switch__slider switch__round"></span>
    </div>
  </div>
  <span class="category-switch__category category-switch__category--1">Male</span>
  <span class="category-switch__category category-switch__category--2">Female</span>
  <span class="category-switch__title">gender</span>
</div>

And the SCSS code:

.category-switch {
    // Grid setup for item placement
    display: grid;
    grid-template-columns: repeat(3, min-content);
    grid-template-rows: repeat(3, min-content);
    gap: 0.8rem;
    place-items: center;
    justify-items: center;
    // Component width based on content
    width: max-content;

    // Title styling
    &__title {
        grid-row: 1/2;
        grid-column: 2/3;
        font-weight: bold;
        text-transform: capitalize;
    }

    // Category text positioning
    &__category {
        &--1 {
            grid-row: 2/3;
            grid-column: 1/2;
        }

        &--2 {
            grid-row: 2/3;
            grid-column: 3/4;
        }
    }

    // Switch position setting
    &__switch {
        grid-row: 2/3;
        grid-column: 2/3;
    }

    // Button CSS
    &__btn {
        grid-row: 3/4;
        grid-column: 2/3;
        display: grid;
        place-items: center;
        position: relative;
        width: 7rem;
        height: 2.8rem;
        background: #d02b2b;
        border-radius: 0.5rem;
    }
}

I aimed for minimal code and omitted any non-positioning related SCSS details.

Answer №1

Previously, I wrote the following... Apologies for any differences in class names. This is simply a template.

        #mainContainer{
            display:grid;
            grid-template-columns: 100px fit-content(10%) 100px;
            column-gap: 20px;
            grid-row-gap: 20px;
            /* adjust your template here */
        }
        #mainContainer div{
            display:grid;
            align-content: center;
            justify-content: center;
            border:1px solid #000000;
        }
        .top{
            font-size:1.6em;
            font-weight: bold;
            grid-column-start: 1;
            grid-column-end: 4;
            grid-row-start: 1;
            grid-row-end: 1;
        }
        .left{
            font-size:1.6em;
            font-weight: bold;
        }
        .right{
            font-size:1.6em;
            font-weight: bold;
        }
        .bottom{
            background-color: orangered;
            border-radius: 10px;
            height:30px;
        }
    <div id="mainContainer">
        <div class="top">
            Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit
        </div>
        <div class="left">
            male
        </div>
        <div class="center">
            <img src="https://dummyimage.com/100x30/a6a6a6/fff" alt="image">
        </div>
        <div class="right">
            female
        </div>
        <div></div>
        <div class="bottom">
            Disable
        </div>
        <div></div>
    </div>

I trust this may be of assistance. Wishing you a pleasant day.

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 img-fluid class is not properly adjusting the height of the image

I'm currently working with Bootstrap 4 and facing a challenge with creating a grid of 4 images - 2 on top and 2 at the bottom. I've applied the img-fluid class, but the image resizing is based solely on width, leading to the height being too larg ...

Unable to upload file in CodeIgniter

Here is a custom function in Codeigniter for uploading files: public function doctor_signup() { $this->load->library('encrypt'); $rand = time() . rand(0, 9999); if($_FILES["file"]["name"]!="") { $config['upl ...

Unusual behavior observed when calculating in Angular

Utilizing Angular.js, I dynamically calculate the height and add the value to the CSS style attribute within an ng-repeat loop. The issue arises with this particular line of code: <div style="height: {{60.0 / 100.0 * (100 - (100.0 / 0.27 * (item.wert ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Encountering a problem with the syntax '[checked]= true' in Angular2

I am currently working on a system for managing orders within restaurants using an angular2 application. The code I have is as follows: <md-radio-group> <span *ngFor="let extIng of item.extra_ingredients;"> <md-radio-button *ngIf= ...

tips on displaying information in a vertical tab orientation

I'm struggling to figure out how to loop inside the <TabPanel> in order to render data using React vertical tabs. I've provided the code I've tried and the data coming from an API. Check out the codesandbox at https://codesandbox.io/s/ ...

in Vue.js, extract the style of an element and apply it to a different element

Currently, I am using VUE.js 2 in my project. Here is my website's DOM structure: <aside :style="{height : height()}" class="col-sm-4 col-md-3 col-lg-3">...</aside> <main class="col-sm-8 col-md-9 col-lg-9" ref="userPanelMainContents" ...

Utilizing an alternative HTML design with the identical XSL style sheet

Can a single XSLT stylesheet be used with different HTML layouts? In my exploration of XSLT, I've noticed that most examples have the HTML code embedded within the stylesheet itself. Is it feasible to apply the same stylesheet to various HTML layout ...

When deployed, Angular 14 and Bootsrap 5 are functioning properly on a local environment but encountering issues on an online

My Angular application (version 14.2.0) is integrated with bootstrap (version 5.2.3). Upon building and deploying the application on a local IIS server, everything displays correctly as shown in the image below: https://i.sstatic.net/pLDs6.jpg However, w ...

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

Update TinyMCE settings on the fly

On my website, I have implemented Tinymce for content editing. However, when users upload files (such as images, videos, or other files) using Tinymce, they are all uploaded to the default folder defined in the TinyMCE config.php file. The issue arises w ...

What is the best way to create a clickable image with a box-shadow when a z-index of -1 is applied?

Is there a way to make an image clickable while still retaining the box shadow effect created using CSS3? Currently, I have set the z-index of -1 for the img tag to apply the box shadow. However, this makes the image not clickable when an href tag is added ...

Anime.js: Grid layout causing issues with displaying simple text animations

I'm attempting to create a text animation within a grid layout using the anime.js library, but unfortunately, the animation isn't displaying. The project consists of just one HTML file. The JavaScript code: <script> import anime from &ap ...

When using JavaScript, I have noticed that my incremental pattern is 1, 3, 6, and 10

I am currently using a file upload script known as Simple Photo Manager. Whenever I upload multiple images and wish to delete some of them, I find myself in need of creating a variable called numDeleted (which basically represents the number of images dele ...

providing the PIE.htc file from the developer server within Visual Studio 2010

Has anyone had success serving the developer server on Visual Studio 2010 with the PIE.htc file? Unfortunately, PIE.htc is not functioning properly when attempting to run my web application on the local developer server. Any suggestions or hints would be ...

Form a triangle in order to prevent the inner content from spilling out

I'm currently attempting to design a triangle shape that prevents the inner content from overflowing while still allowing the inner content to be draggable. So far, I have experimented with various solutions such as polygons and canvas, but none of t ...

JavaScript Polling Based on Time

I am currently working on developing an alarm clock feature using the Date() object. My aim is to have a function trigger when the time from the date object matches the time set by the user. Users set their alarms by selecting a specific time, but I' ...

How can I create a tooltip or something similar for an HTML input field?

Seeking a solution for adding additional information to an HTML input field while typing or hovering over it. Attempted the following code snippet: <input type="text" onmouseover="window.status='hello world'; return true;" name="TextInput" ta ...

Retrieving the status of a checkbox using jQuery to obtain a value of 1 or

Incorporating jQuery, I am able to retrieve the values of all input fields using the provided code snippet. However, an issue arises when dealing with checkboxes as they return "on" if checked. How can I modify this to receive a value of 1 when a checkbox ...

Angular and WEB API experiencing issues with the update function synchronization

Currently, I'm developing a CRUD example using dotnet core and Angular. In the backend, I have implemented a function in the CarController.cs as shown below: CarController.cs [Route("UpdateCar")] [HttpPut] public IActionResult Put([ ...