How to vertically center align divs of unpredictable height

Currently grappling with a dilemma related to the vertical-align attribute and floating div elements. The heights of these divs are unknown as they are dynamically created based on text content.

If you want to take a look at the code snippet, here is the link: https://jsfiddle.net/zjzyryae/

#test {
  background: yellow;
  display: inline-block;
}
#block1 {
  float: left;
  display: inline-block;
  background-color: grey;
}
#block2 {
  background-color: green;
  float: left;
}
<div id="test">
  <div id="block1">
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
  </div>
  <div id="block2">
    sample
  </div>
</div>

My goal is to vertically center the "block2" div using CSS alone (no JavaScript allowed).

The crucial factor here is that the height of the parent "test" block is dictated by the presence of "block1," rather than being explicitly defined in pixels.

I've scoured various resources but haven't found an exact solution to my unique scenario. The examples I've come across so far have not been applicable to this specific case.

For example, this question about vertically centering text in a dynamic height div relies on setting fixed heights - unlike my scenario.

Similarly, this guide on aligning floating elements vertically does not match my situation as it assumes the parent height matches the child div heights.

I've explored various options like tweaking the display: table property, but so far, no luck.

Answer №1

If you want a responsive design, I recommend using flexbox with the property display: inline-flex. This will allow the elements to "shrink to fit" just like other inline elements. Additionally, using align-items: center will align all flex items to the middle of the container.

#test {
  background: yellow;
  display: inline-flex;
  align-items: center;
}
#block1 {
  background-color: grey;
}
#block2 {
  background-color: green;
}
<div id="test">
  <div id="block1">
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
  </div>
  <div id="block2">
    sample
  </div>
</div>

If older browser support is necessary, consider using inline block (without floats) and adding vertical-align: middle. Be sure to eliminate any unwanted white space.

#test {
  font-size: 0; /*remove white space*/
  background: yellow;
  display: inline-block;
}
#block1,
#block2 {
  font-size: 16px; /*reset font size*/
  display: inline-block;
  vertical-align: middle;
}
#block1 {
  background-color: grey;
}
#block2 {
  background-color: green;
}
<div id="test">
  <div id="block1">
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
  </div>
  <div id="block2">
    sample
  </div>
</div>

An alternative method is to use CSS tables with vertical-align: middle. Note that this will vertically center the content inside the element rather than the element itself or its siblings. You can add a <span> for styling purposes.

#test {
  background: yellow;
  display: inline-table;
  vertical-align: middle;
}
#block1,
#block2 {
  display: table-cell;
  vertical-align: middle;
}
#block1 {
  background-color: grey;
}
/* #block2 {
  background-color: green;
} */
<div id="test">
  <div id="block1">
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
  </div>
  <div id="block2">
    <span style="background:green;">sample</span>
  </div>
</div>

Answer №2

If you are looking to avoid using flex, it is recommended not to rely on float. Instead, consider using only inline-block along with vertical-align:

    #test {
      background: yellow;
      display: inline-block;
    }
    
    #block1 {
      display: inline-block;
      background-color: grey;
      vertical-align:middle;
    }
    
    #block2 {
      display: inline-block;
      background-color: green;
      vertical-align:middle;
    }
<div id="test">
  <div id="block1">
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
  </div><!--
  --><div id="block2">
    sample
  </div>
</div>
https://jsfiddle.net/zjzyryae/1/

Answer №3

Flexbox is a great solution for this

#container {
        background: yellow;
        display: flex;
        align-items: center;
    }

Answer №4

Have you considered using display flex for all of them? It's a new technique worth experimenting with. Start off with flex from the beginning and adjust the structure of your CSS code.

This is all the advice I can offer.

    div#test {
        background: yellow;
        display: flex;
      flex-direction:row;
    }

div#block1, div#block2{
display:flex;
flex-direction:column;}
    div#block1 {
        background-color: grey;
    }

    div#block2 {
        background-color: yellow;
      align-items:center;
      justify-content:center
    }
    div#inside-block2{
        background-color:green;
    }
<div id="test">

    <div id="block1">
        <div>test</div>
        <div>test</div>
        <div>test</div>
        <div>test</div>
        <div>test</div>
        <div>test</div>
        <div>test</div>
        <div>test</div>
        <div>test</div>
        <div>test</div>  
    </div>

    <div id="block2">
      <div id="inside-block2">
        sample
      </div>
    </div>

</div>

So what I have done is created a container called test with child elements block1 and block2, where block2 has a customizable child element that you can position as needed. To learn more about flexbox, check out this link.

As for some coding tips, use div#id to reference an ID in your CSS. Some browsers may behave inconsistently if you only use #id for IDs.

I hope this information proves helpful to you.

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

Increase the size of the box-shadow so that it extends beyond the boundaries

Can we create a wider box-shadow in CSS than the actual HTML element it is being applied to, while maintaining the same height as the element? Increasing the spread of the shadow typically increases the height as well. In the provided code snippet, the max ...

I am looking to modify the background color of characters in a text box once the characters in a textarea exceed 150 characters

Currently, I am utilizing event.data to capture the text inputted into this particular HTML textbox. My intention is to change the background color to red based on that input. However, when using the style attribute on event.data, I encounter an error. It& ...

Adjust the width of Google chart to 100% automatically when the page is resized in Angular version 4 or higher

My application has numerous responsive wrappers on the site, each predefined from an API and containing a Google chart. The problem is that when the page initially loads, the charts are rendered at a specific size, and resizing the window only affects the ...

Improving the style of Google Maps InfoWindows for right-to-left languages

I'm currently working on a Google Maps marker infowindow and trying to adjust the padding specifically for RTL languages. Here's what I've attempted so far: google.maps.event.addListener(marker, 'click', function () { i ...

Difficulty in preventing the website from reloading when accessing tabs

I am working on a function that allows users to access the content of a tab without causing the page to reload. Initially, I tried using something like $( "#tab1" ).click(function() { $("#content").load("tab1.html #content > *"); }); but unfortun ...

What is preventing NgClass from applying the CSS styles?

I'm currently facing an issue in Angular2 where I am trying to apply different styles using ngClass within an 'NgFor' loop, but for some reason, it's not working as expected. Apologies for any language errors. <div class='line ...

What is a neat trick to conceal an image when we hover over it?

Within my project, I have a grid layout showcasing images of various items through ng-repeat. My goal is to have the images disappear upon hover, and be replaced by a new div of equal size containing all the sub-components of the item. However, instead o ...

Leverage jquery to adjust the height or width of an element depending on which dimension is larger

I'm a beginner in jquery and html and am currently developing a gallery webpage. The functionality involves setting the selected image as the page background and then scrolling vertically based on the mouse pointer's position. This works well for ...

What is causing vertical-align:middle to not function in the same way as text-align:center?

Is there a reason why vertical-align:middle doesn't seem to work as easily as text-align:center? It's frustrating that it's so challenging to get it right. I'm curious why the folks at W3C haven't created something like text-alig ...

IE6 is not displaying the tag styles correctly

My website has a section that shows two links next to each other. While it's displaying correctly on most browsers, it seems to have issues specifically in IE6. You can view the issue on this fiddle. Can anyone shed some light on why this is happenin ...

Tips for improving the loading speed of my website

What are the best ways to improve website optimization and increase page speed? I have already minified JavaScript and CSS, as well as optimized images, but Google continues to penalize our pages. Any suggestions? ...

What is the correct method to define the width as a percentage while also maintaining a minimum width in pixels?

My header/navigation bar div features a repeat-x background image. Within this, I have a horizontal navigation that needs to be centered over the background with a specified min-width and normal width. I want the navigation to be 80% of the full width, wi ...

Optimize the height of embedded Linkedin posts for a seamless viewing experience without the need for scrolling

I have noticed that in LinkedIn embedded posts on my page, each post has a different height and there are scrolls. Is there a way I can make the height dynamic according to the post height? <iframe src="https://www.linkedin.com/embed/feed/update/ur ...

Files are nowhere to be found when setting up an angular project

After creating an Angular project, I noticed that some key files were missing in the initial setup, such as app.modules.ts and app-routing.modules.ts The project was generated using the command ng new name Here is a screenshot displaying all the files th ...

Is it possible to enlarge a div using "display: table-cell" property when clicked on?

There are various components displayed on my webpage: I require all components to have a minimum height of 150px. If the height is less than 150px, I want to vertically center their text. In case the height exceeds 150px, I aim to truncate the text at 15 ...

Incorporating an image within a table while maintaining 100% height: A step-by-step guide

I'm struggling to make the image fit 100% to the height of a CSS-created table. The table and image seem to be ignoring the dimensions of the parent element, as shown below. Since everything needs to be dynamic, I am working with percentages. .img ...

Custom Pug design without any CSS files added

I am having trouble with my .pug template in my express project as it is not including its stylesheets. I have referred to the pug documentation but still can't figure out the issue. Any help would be appreciated! FILE TREE: views `-- index.pug `-- ...

Getting rid of the excess white space below the footer caused by concealed elements

In my design, I have three columns. The rightmost column is filled with 'Divs' containing collapsed information that can be scrolled through using the mouse wheel. The overflow in the center is hidden. The width of all three columns is set to 760 ...

Combining inline input fields and select buttons with Bootstrap 3

I've been exploring different ways to align form elements inline, including dropdown buttons and select buttons, but have only had success with smaller size buttons around 40px wide. My main challenge now is trying to create a search bar with an input ...

Updating the Background Color of a Selected Checkbox in HTML

I have a straightforward question that I've been struggling to find a simple answer for. Can anyone help me with this? Here's the checkbox code I'm working with: <input type="checkbox"> All I want to do is change the backgr ...