Aligning a child element with siblings within a parent div

I'm trying to create a layout where the grandparent div has multiple parent divs, each with different numbers of elements. In one type of parent div with 3 elements, the second element should always be aligned in the center. The first and third elements in this type of parent div need to touch the second element and adjust towards the edges only if their content increases. I want to achieve this using CSS without messing up the relationship between these elements. Most online solutions suggest using margins or absolute positioning, but they disrupt the alignment between the elements.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="grandparent">
  <div class="parent">
    <span class="left-side">First Text!</span>
    <span class="must-be-centered">SOME TEXT!</span>
    <span class="right-side">Other Text!</span>
  </div>
  <div class="parent">
    <span class="must-be-centered">SOME TEXT!</span>
  </div>
</div>

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

The important thing is that the large yellow element in the center is perfectly centered, while the left and right elements are touching it. Even in the div with just one element, the single element remains centered.

Answer №1

Utilize grid to divide the .parent element into 3 sections, with equal length on the left and right sides while aligning text to the right on the left side

.parent {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
}

.left-side {
  text-align: right;
}

.must-be-centered { 
  grid-column-start: 2;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="grandparent">
  <div class="parent">
    <span class="left-side">First Text!</span>
    <span class="must-be-centered">SOME TEXT!</span>
    <span class="right-side">Other Text!</span>
  </div>
  <div class="parent">
    <span class="must-be-centered">SOME TEXT!</span>
  </div>
</div>

Answer №2

To horizontally center-align your columns, you can utilize flexbox. The .child class will interact with sibling elements that have an immediate parent property with display: flex

.grandparent {
  background-color: #18bbf0;
  padding: 12px;
  color: #fff;
  font-family: Arial;
  text-align: center;
}
.parent { 
  display: flex; /* control child behavior */
  justify-content: center; /* horizontal centering */
  background-color: #fff;
  padding: 12px;
}
.child {
  background-color: #18bbf0;
  padding: 12px;
}
<div class="grandparent">
  <div class="parent">
    <div class="child">First Text!</div>
    <div class="child">SOME TEXT!</div>
    <div class="child">Other Text!</div>
  </div>
  <div class="parent">
    <div class="child">SOME TEXT!</div>
  </div>
</div>

Answer №3

Here is a helpful starting point for you.

#parent {
  width: 100vw;
  height: 100vh;
}

.row {
  display: flex;
  justify-content: center;
  background: blue;
  height: 200px;
  align-items: center;
}

.row > div {
  background: yellow;
  height: 100px;
  margin: 0 10px;
  border: 1px solid red;
  width: 150px;
}

.row > div:only-child,
.row > div:nth-child(even) {
  flex: 0 0 400px;
}
<div id="parent">
  <div class="row">
    <div></div>
    <div></div>
    <div></div>
  </div>
  <div class="row">
    <div></div>
  </div>
</div>

Answer №4

Utilizing Bootstrap classes, the code would be structured as follows (without any additional CSS)...

<div class="grandparent min-vh-100 d-flex flex-column align-items-center justify-content-center">
  <div class="parent">
    <span class="left-side">First Text!</span>
    <span class="must-be-centered">SOME TEXT!</span>
    <span class="right-side">Other Text!</span>
  </div>
  <div class="parent">
    <span class="must-be-centered">SOME TEXT!</span>
  </div>
</div>

Answer №5

Creating layouts like this becomes effortless with Flexbox. For the .must-be-centered divs, make sure to utilize the flex: 1 0 auto; property for flexibility and the max-width attribute to control its size.

body {
  background: red;
}
.parent {
  background: blue;
  display: flex;
  justify-content: center;
  margin: 0 0 20px;
  padding: 20px;
}
.parent > span {
  background: yellow;
  text-align: center;
  margin: 0 10px;
  padding: 20px;
}
.must-be-centered {
  flex: 1 0 auto;
  max-width: 200px;
}
<div class="grandparent">
  <div class="parent">
    <span class="left-side">First Text!</span>
    <span class="must-be-centered">SOME TEXT!</span>
    <span class="right-side">Other Text!</span>
  </div>
  <div class="parent">
    <span class="must-be-centered">SOME TEXT!</span>
  </div>
</div>

Answer №6

Providing some basic code snippets to cover various scenarios. Hopefully, this will be helpful for you. Thank you.

.grandparent {
  background-color: red;
  height: 100vh;
  padding: 10px;
}

.parent {
  background-color: blue;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  min-height: 100px;
}

span {
  background-color: yellow;
  padding: 10px;
}

.must-be-centered {
  margin: 0 10px;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="grandparent">
  <div class="parent">
    <span class="left-side">First Text!</span>
    <span class="must-be-centered">SOME TEXT!</span>
    <span class="right-side">Other Text!</span>
  </div>
  <div class="parent">
     <span class="must-be-centered">SOME TEXT!</span>
  </div>
</div>

Answer №7

If you're looking to center elements in a clean and simple way, consider using the display:flex property. Just add the following code snippet to your parent element:

.parent {
  display:flex;
  justify-content:center;
}

Answer №8

When discussing alignment, it appears you are focusing on vertical rather than horizontal alignment. Achieving this can be simple using flex:

.grandparent{
    display: flex; 
    flex-direction: column;
} 
.parent{
    display: flex;
    justify-content:center;
    align-items:center;
}

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

Executing HTTP requests in ngrx-effects

I'm currently working on an Angular REST application using ngrx/effects and referencing the example application available on GIT. I am facing challenges while trying to replace hardcoded JSON data in effects with data from an HTTP REST endpoint. The e ...

Create a Bootstrap multi-bar component for visually displaying the daytime information

I am looking to create a horizontal bar with multiple intervals. Here is what I have tried so far: <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"& ...

What is the best way to center CSS content such as boxes and text?

As a beginner in CSS tutorials, I am seeking guidance on how to center the entire content in the browser. Below is the CSS code that needs attention. Additionally, there is a screenshot of the current output included for reference. body { background:#E9 ...

"Unveiling the invisible: Revealing hidden characters in PHP

Currently I am dealing with some code extracted from a MySQL column. Within this code are hidden characters like "\t" and "\n". I am attempting to showcase the raw code in a DIV while also making sure these hidden characters are visible. The cod ...

Using the PMT function in PHP allows for easy calculation of

I have been attempting to integrate the PMT function into my PHP code for a loan calculator. Unfortunately, the PHP code seems to be malfunctioning and I am unsure of the reason, especially since I am still at the novice level in programming. PHP(Get.php ...

Tips on adjusting the placement of a div element with JavaScript

Initially, I am unsure if the title accurately reflects what I am seeking. Within my HTML form, I have numerous elements such as div, p, or js. Here is an example: <div id="main"> <div id="abc1"></div> <div id="abc2"></div&g ...

Is there a way to restrict my input to only 10 numbers without allowing any characters?

Is there a way to restrict the phone number input to only allow 10 numbers and exclude any other characters? Currently, setting the maxLength attribute limits the characters to 10 but allows additional characters as well. If I change the type attribute to ...

Loading dynamic images in HTML using Javascript and Django templates

Attempting to load a specific image using javascript within a django template has presented challenges due to the formatting of django tags. The standard django static asset source in an img tag looks like this: {% load static %} <img src="{% static & ...

Maintaining the order of list items while utilizing jQuery sortable功能

Check out my JSFiddle link here I am utilizing the jQuery sortable function to enable sorting of 3 columns. My goal is to ensure that when a name is moved from column 2 or 3 to column 1, the names in columns 2 and 3 remain unaffected, maintaining their al ...

Replicate the Bootstrap flexbox grid system with customized media breakpoints

I'm trying to replicate the flexbox grid system found in Bootstrap. Everything is working smoothly except for the media query aspect. The columns are stacking horizontally as intended, but when a specific breakpoint is reached, I aim to have the divs ...

Global variable appears undefined in Angular 2 view, yet it is still displaying

I'm running into issues with my Angular 2 code. Inside my ts file, I have the following: import { Test } from '../../../../models/test'; import { TestService } from '../../../../services/test.service'; import { Job} fr ...

Internet Explorer fails to load stylesheets for elements loaded with .load() and JavaScript functionality is also disabled

I'm using the .load() function to load my content, as shown in this code: $(document).ready(function(){ $("nav a").click(function () { $("#main-content").load($(this).attr("href") + " #content > *"); return false; }); }); The sty ...

Struggling to center an image within a CSS border

I'm attempting to include a subtle border around an icon. The issue I am facing is that the image is positioned at the top of the bordered area, whereas I want it centered. Here's how it currently appears: This is my current border CSS style: ...

To combine both jquery-1.min.js and jquery.min.js is essential for achieving optimal functionality

When using these two files, only one of them can work on a page. <script src="jquery.min.js"></script> <script src="jquery-1.min.js"></script>//Only the second one works Alternatively, if the order is changed: <script src="jq ...

Insert round sphere shapes in the corners of the cells on the Table

I am working on a GUI representation table that features cells with spheres in the corner. Additionally, the footer contains a plus symbol (font-awesome icon) in the corner. I have attempted to place the sphere so that it aligns only inside the cell. Here ...

Is it acceptable to include a heading element within a label element?

Would it be acceptable to include other elements such as <h1> <h2> <b> within <label> elements, or is it preferable to use style instead? <label for="B"><b>like this</b></label> <label for=" ...

extracting information from a webpage with Php

While the task at hand is straightforward, I am looking to incorporate a form to retrieve the URLs needed. Initially, I utilized file_get_contents but later transitioned to fopen. <?php $page = $_GET['page']; $marki = fopen($page, "rb"); ec ...

Styling Your Pricing Table with a Unique Bootstrap Card Design

Today, I've been working on the bootstrap card lesson and followed along with my teacher. However, the grid markup effect isn't functioning as expected. Initially, I doubted myself and thought I had inputted something wrong, but upon closer insp ...

Overlap in Bootstrap 4 Sections

I'm facing an issue with two sections on my website. They are properly separated until a certain size, https://i.sstatic.net/e52t2.png, but when the size is reduced, they start to overlap https://i.sstatic.net/aMtHr.png. Below is a snippet of my code: ...

Trouble linking CSS file with Plotly Dash interface

Transitioning from plotly to dash, I am looking to incorporate a css file to enhance the appearance of my dashboard. The structure consists of app.py and index.py in the main directory, with an additional style.css file located in the /assets folder. Desp ...