Tips for perfectly aligning the content in a flexbox item vertically

Is there a way to vertically center the contents of a flexbox item while using justify-content:stretch;? The old method of using

display:table-cell;vertical-align:middle;
does not seem to work in this scenario. Is there an alternative solution?

.flex-container {
    display:flex;
    align-items:center;
    justify-content:stretch;
}
.flex-item {
    align-self:stretch;
}

<div class="flex-container">
    <div class="flex-item">I want to be vertically centered! But I'm not.</div>
</div>

BEFORE YOU RESPOND: Please note that my goal is to center the CONTENTS of the flex-item. When using justify-content:stretch, the height of the item stretches to match the container, but the contents remain at the top (especially in Chrome).

"A picture is worth a thousand words." Image (A) demonstrates the current state, while image (B) shows the desired outcome.

Answer №1

To achieve vertical alignment, you can utilize the display property to turn each flex item into a flex container and then use the align-items property for vertical alignment. Here is an example:

.flex-container {
  display:flex;
  align-items:center;
  height: 200px; /* demo purpose */
}

.flex-item {
  align-self:stretch;
  display:flex;
  align-items:center;
  background-color: gold; /* demo purpose */
}
<div class="flex-container">
    <div class="flex-item">
      I want to be centered vertically!
      <s>But I'm not.</s>
  </div>
</div>

Additionally, if you remove the align-items:center; declaration from .flex-container, you can also eliminate align-self:stretch; from the flex items.

Answer №2

It seems like there may be a misunderstanding in your request; you might want to use "flex-grow" instead of "justify-content:stretch;".

In my example, I utilized flex:1 auto; as a shorthand for setting multiple flex properties.

HTML:

<div class="flex-container">
    <div class="flex-item">I'm the top performer!
    </div>
    <div class="flex-item flex-center">
        I aim to be vertically centered! And I've achieved it!
    </div>
</div>

CSS:

*{
    box-sizing:border-box;
    padding:5px;
}
.flex-container {
    border: 1px solid;
    display:flex;
    align-items:center;
    height: 100px;
}
.flex-item {
    flex: 1 auto;
    border: 1px solid green;
    height:100%;
    display:flex;
    justify-content:center;
}
.flex-center {
    align-items: center;
}

http://jsfiddle.net/p28tjskq/

Learn more about the Flex property:
https://developer.mozilla.org/en-US/docs/Web/CSS/flex

Answer №3

In the realm of div-boxes, the text within is a mysterious inline-node. To achieve text centering within your box, employ the following CSS:


    display: flex;
    align-items:center;

However, caution must be exercised to ensure that the use of align-self does not disrupt your desired outcome.

*{
    box-sizing:border-box;
    padding:5px;
}
.flex-container {
    border: 1px solid;
    display:flex;

    height: 200px;
}
.flex-item {
    flex: 1 auto;
    border: 1px solid green;
    align-self:stretch;
    display:flex;
    justify-content:center;
}
.flex-center {
    align-items: center;
}
.flex-center div {
  border: 1px solid blue;
}
<div class="flex-container">
    <div class="flex-item">I'm top dog!
    </div>
    <div class="flex-item flex-center">
        I want to be vertically centered! And I am!    
        <div style="align-self:start;">
          I want to be vertically centered too! But align-self broke it!
        </div>
        <span style="align-self:middle; color:red;">Hello. I am a centered text. </span>
    </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

Steps for embedding the code into your website

I'm facing an issue with integrating a .jsx file into my website. I tried testing it on a single-page demo site, but nothing is showing up. Can someone guide me through the steps to successfully integrate it onto my site? I've also attached the . ...

Discover a seamless way to update both the theme of your spreadsheet and the style and background of

My concept revolves around the ability to change the theme within a spreadsheet, with the HTML sidebar style adjusting accordingly upon reopening based on the selected theme. Initially, I extract color and font styles from the spreadsheet theme. While the ...

Eliminate JavaScript comments with Regex in PHP

Looking to reduce the size of HTML code with the help of PHP and Regex. Here is the minify function: public static function sanitize_output($buffer) { $search = array( '/ {2,}/', '/<!--.*?-->|\t|(?:\r?& ...

Why are Javascript variables not producing the desired result? It seems like they are being treated as strings instead

Why is there an error? Expected result: 1360000 Actual result: 1000000360000 <script> function calculateTotal() { var amount = document.getElementById("borrow").value; var duration = document.getElementById("return").value; var interest = durati ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

Applying a margin to a CSS div at the bottom may cause it to not

I'm struggling to achieve the desired outcome with my layout: https://i.stack.imgur.com/CvLFl.png I have successfully replicated the image, but only when my div is not floating on the page (without margin applied and without using position: absolute ...

Adding a linear gradient with a fade effect to Highcharts sparkline chart: Step by step guide

I am working with a Highcharts sparkline chart, and the design in my Figma file resembles the image provided below. I would like to customize the chart by adding transparency and a linear-gradient effect. Can anyone provide guidance on how to achieve this? ...

Use JavaScript to smoothly move a span to a specific location on the page

My challenge lies in enabling users to dynamically create a span at any desired location upon clicking the "Link" button. The issue I'm facing is that although I set the attribute draggable="true" for the dynamically created span, it remains fixed wit ...

Tips for styling an inline list using CSS before revealing it with jQuery's .show method:

In my project, I want to display a row of 'cells' which are simply images of black or white squares based on their ID. The issue I am facing is that when the button is clicked, the row list is shown without the CSS applied, and then after a brief ...

Clear navigation bar alternative

My website features a transparent bootstrap navbar, with the hero header as the second element on the page set at a -50 margin to place it behind the menu, creating the desired effect. However, I have encountered an issue on certain pages where there is n ...

Eliminating characteristics and rejuvenating the component

I have divs on my webpage that I want to keep hidden until a specific element is clicked. When trying to hide them, I encountered three options: visibilty: hidden - I didn't like this because the hidden div still took up space in the layout. displa ...

What is the best way to send JSON data to Sass in ReactJS?

In my current project, I am developing a React/Redux application with Webpack that showcases UI components and enables users to adjust the colors of those components. The styling is being done using CSS Modules with scss. My preference is to keep all the s ...

Managing images within a bootstrap column: Tips and tricks

I'm using a bootstrap col-md-1 with an image inside, wrapped in a div with padding. The issue is that the image is too small and I want it to be at least as big as the original size, https://i.sstatic.net/9hqyj.png while still being responsive. An ...

Is it just me, or does the float left - float right combination only break in IE

Oh dear, it seems like IE9 is causing some trouble again. The other "capable" browsers handle this HTML just fine, including IE8 which isn't even that great. Here's the code snippet: <div class="contact_info_city" id="contact_info_cityX"> ...

Is there a way to limit HTML wrapping to 79 characters in TextMate?

I'm currently using TextMate to work on my HTML projects. When I select View > Wrap > 79 characters for certain types of content, it wraps at 79 characters as expected. But when it comes to working with HTML, this feature doesn't seem to ...

Headlining the Border

My goal is to separate various headlines (along with their images) by using a bottom-border. I attempted this, but instead of putting a border between headlines, it ends up on the image. Using jQuery $(document).ready(function() { $.ajax({ url: "h ...

Mastering Bootstrap: Achieving flawless column stacking in succession

I am currently integrating bootstrap into my existing HTML code, but I only require it in two specific sections to avoid rewriting the entire code. Everything looks fine on my 1080p screen as intended. However, when I resize the screen slightly The titl ...

The alignment of the Bootstrap 4 row is off-center

My bootstrap structure includes a row with 4 columns, initially set up with 3 columns containing icons that aligned perfectly. Upon adding a fourth column, the new addition appears slightly lower on the page compared to the rest, resulting in misalignment. ...

Change the background color of a checkbox with jQuery by toggling it

I'm currently utilizing the Bootstrap Tree to generate a nested checkbox list (). However, I am looking to enhance the user experience by highlighting the checked items, and ensuring that when a parent is selected, its children are also highlighted. W ...

Changing base 64 into Mp3 audio format using PHP

I currently have an "audio" tag with a script (which is essentially a plugin) that receives and saves it as base64. This functionality is working properly. My goal now is to modify the script in order to send the base64 data to the server, convert it to m ...