Ways to position a child element at the center of its parent container?

Hey there, is there a way I can achieve this specific layout without relying on position: absolute? Flexbox would be the preferred method. The main goal here is to have the middle element horizontally centered within its parent element, regardless of other elements present. I am currently using the following CSS for the middle element (as it needs to be in the middle of the window):

position: absolute;
left: 50%;
transform: translateX(-50%);

However, with this approach, the parent does not adjust to the height of the middle element, making it less than ideal for my case.

Note: I did attempt to use this as well:

display: flex;
justify-content: space-between;
align-items: center;

But unfortunately, it did not yield the desired outcome (the line should split the first two middle blocks exactly in half):

#container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-style: solid;
  border-color: black;
  margin: 4px;
  padding: 4px;
}

#block {
  background-color: red;
  height: 40px;
}

#middle-line {
  border: none;
  border-left: dashed;
  position: absolute;
  height: 100%;
  left: 50%;
  width: 1px;
}
<html>

<body>
  <hr id="middle-line">

  <div id="container">
    <div id="block" style="width: 120px"></div>
    <div id="block" style="width: 40px"></div>
    <div id="block" style="width: 40px"></div>
  </div>
  <div id="container">
    <div id="block" style="width: 40px"></div>
    <div id="block" style="width: 40px"></div>
    <div id="block" style="width: 120px"></div>
  </div>
  <div id="container">
    <div id="block" style="width: 40px"></div>
    <div id="block" style="width: 40px"></div>
    <div id="block" style="width: 40px"></div>
  </div>
  <div id="container">
    <div id="block" style="width: 120px"></div>
    <div id="block" style="width: 40px"></div>
    <div id="block" style="width: 120px"></div>
  </div>
</body>

</html>

Answer №1

You might want to experiment with the following:

display: flex;
justify-content: space-between;

This snippet should be placed within the code block like so:

.section {
    align-items: center;
    display: flex;
    justify-content: space-between;
}

The sequence of this code is not critical. (There may be a syntax issue as I am more familiar with Sass.)

Answer №2

Stumbled upon the solution on social media

https://twitter.com/EricVicenti/status/1645496262161203202

.example1 .block-1 {
  width: 40px;
}

.example1 .block-2 {
  width: 125px;
}

.example2 .block-1 {
  width: 175px;
}

.example2 .block-2 {
  width: 25px;
}

.example3 .block-1 {
  width: 40px;
}

.example3 .block-2 {
  width: 100px;
}


html, body {
  width: 100%;
  height: 100%;
  display: flex;
  padding: 0;
  margin: 0;
  flex-direction: column;
  align-items: center;
  font-family: system-ui;
  background-color: #f5f5f5;
}

.root {
  background-color: white;
  margin-top: 25px;
  border-color: gray;
  border-style: solid;
  border-width: 3px;
  padding: 10px;
  width: 450px;
  
  display: flex;
  flex-direction: row;
  align-items: stretch;
  justify-content: flex-start;
}

.left-container, .right-container {
  flex-basis: 0%;
  flex-grow: 1;
  flex-shrink: 1;
  
  display: flex;
  flex-direction: row;
  align-items: stretch;
  justify-content: flex-start;
}

.spacer {
  flex-grow: 1;
  flex-shrink: 1;
}

h1 {
  margin: 0;
  padding: 0;
  font-weight: normal;
}

.text {
  flex-basis: auto;
  flex-grow: 0;
  flex-shrink: 1;
  
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding-left: 10px;
  padding-right: 10px;
}

.block {
  background-color: #5744ff;
  flex-grow: 0;
  flex-shrink: 0;
}
<!-- Credit: https://twitter.com/vincentriemer/status/1645525394542723072 -->

<div class="root example1">
  <div class="left-container">
    <div class="block block-1"></div>
    <div class="spacer"></div>
  </div>
  <h1 class="text">Title</h1>
  <div class="right-container">
    <div class="spacer"></div>
    <div class="block block-2"></div>
  </div>
</div>

<div class="root example2">
  <div class="left-container">
    <div class="block block-1"></div>
    <div class="spacer"></div>
  </div>
  <h1 class="text">Pushed Title</h1>
  <div class="right-container">
    <div class="spacer"></div>
    <div class="block block-2"></div>
  </div>
</div>

<div class="root example3">
  <div class="left-container">
    <div class="block block-1"></div>
    <div class="spacer"></div>
  </div>
  <h1 class="text">Title may be very long</h1>
  <div class="right-container">
    <div class="spacer"></div>
    <div class="block block-2"></div>
  </div>
</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

Paginating: Restrict the page number for smaller screens

When viewing on a small screen device (> 641 px), my pagination should resemble https://i.sstatic.net/dSSUX.png Conversely, on screens that are medium-sized and larger (< 641 px), the pagination should appear as shown here: https://i.sstatic.net/C1E ...

Switch up the link color when it pops up

Is there a method to change the link color to gray without encountering glitches like on my site, where it mistakenly shows "Quick Nav."? Click here to view the page with the glitch I only want this particular link to be bold and not any other links. He ...

Navigating Struts - The art of breaking free from encoded symbols in a text field

I'm having trouble displaying the trademark symbol in a default text within a Struts text field. Despite trying various methods, the symbol does not appear and only outputs the code instead. Can someone please provide guidance on how to properly displ ...

Ways to extend the length/size of the HTML5 range input type

Is there a way to adjust the length or size of the HTML5 range input for it to appear longer or bigger? <!DOCTYPE html> <html> <body> <form action="/" method="get"> Points: <input type="range" name="points" min="0" max="10"& ...

execute the code when the device is not an iPad

if ( (navigator.userAgent.indexOf('/iPadi') != -1) ) { } This conditional statement is used to identify whether the user's device is an iPad, but I specifically want to execute the code only if it is not an iPad. I have a JQuery hover func ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Injecting HTML with jQuery and AJAX and Implementing Gallery Plugins

In my exploration of jQuery and loading HTML from external files, I've encountered a problem. My goal is to extract a URL parameter, use it to load a file named data.html where the data represents the parameter value for gallery, inject the content of ...

Is the user currently browsing the 'Home screen webpage' or using the Safari browser?

In JavaScript, is there a method to determine if the user has accessed the website from their home screen after adding it to their home screen, or if they are browsing via Safari as usual? ...

Is there a way to dynamically change the source of an image based on different screen sizes using Tailwind CSS?

Currently, I am utilizing the next/Image component for setting an image and applying styling through tailwindcss. However, I have encountered a roadblock at this juncture. My Objective My goal is to dynamically change the src attribute of the image based ...

Auto-selecting the first item in a CSS menu when the switcher is tapped on mobile devices

Struggling with a responsive CSS menu on my website, . The switcher on mobile seems to automatically click the first item in the menu (Home) as I open it, redirecting me instantly. When setting the link to "#" everything is fine, but then I lose the home l ...

Empty the password field

<input name="e_password" id="e_password" type="password" autocomplete="off" /> The password field above is causing some trouble as it gets automatically filled in Mozilla, but not in Chrome and IE11. This seems to be retaining values from previous a ...

dragging and dropping files for easy upload

Here is a challenge I am facing: I am looking for a solution that allows users to drag multiple images from their local file system onto the flash/flex/html5 app. The app should then extract the file name details and communicate with the server. Once t ...

Attempting to replicate the flipping motion of a card by applying the transform property to rotate a div element, ultimately revealing a different

I am attempting to create a series of divs that simulate the flipping action of a notecard. Unfortunately, when I hover over the div, it turns white because I have set the display property to none. I am unsure how to make the other div (.back) visible. Y ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

Customizing the layout of a Bootstrap carousel by adding HR lines both above and

I have set up a bootstrap carousel to showcase numerous images, with the carousel indicators serving as image icons. I am looking to add horizontal lines above and below these icons. How can I achieve this? Currently, the icons functioning as carousel ind ...

Tips for maintaining the selected radio button state after refreshing the JSP page: Ensuring that the radio button remains selected

I need help with refreshing a page after clicking on one of two radio buttons. I've tried multiple solutions but haven't been successful so far. Can someone assist me? <script> $(document).ready(function() { $(document).on('c ...

Responsive design

Is it possible to change the background-color of the h1 element when the browser ratio is 4:3? I've attempted using the aspect-ratio property in my media query, but it doesn't seem to be working. Any suggestions on how to resolve this issue? Che ...

CSS Problem with Image Overlapping

Attached is an image that I would like to design in HTML. It has been quite successful, but when testing it on different resolutions, the red box seems to move around. The design was created with 100% width and height. <style type="text/css"> ...

Mastering the art of manipulating Div elements using CSS for the optimal Print View experience

I have a table with several columns and 1000 rows. When I print the page, it breaks the rows onto different pages, showing the remaining rows on subsequent pages. I want to display the complete record in one go. Below is a sample code with only one row in ...

The Add/Remove button functionality is not functioning as expected for duplicated form fields when using jQuery

I am experiencing an issue with the functionality of the "Add another" and "Remove row" buttons in my form. I implemented code from a specific Stack Overflow answer (jquery clone form fields and increment id) to create a cloneable section, but only the ori ...