Home  >  Article  >  Web Front-end  >  How to Align Vertical Content Horizontally in Flexbox Columns?

How to Align Vertical Content Horizontally in Flexbox Columns?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 18:25:02319browse

How to Align Vertical Content Horizontally in Flexbox Columns?

Balancing the Height of Children in Different Parents with Flexbox

Question:

In a two-column layout where each column contains content of varying lengths, how can we ensure that the lists in both columns remain aligned horizontally without breaking Bootstrap's mobile optimization? Ideally, a solution should leverage Flexbox and avoid JavaScript.

Answer:

To achieve this without JavaScript, we need to make all content items (heading, paragraphs, and lists) siblings in the markup.

When the screen width allows for side-by-side display of columns, these items will need to be reordered to maintain proper alignment:

  • Media Query:

    <code class="css">@media (min-width: 768px) {
      // Flexbox rules
    }</code>
  • Flexbox Configuration:

    <code class="css">.content {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
    }
    
    .content > * {
      flex-basis: calc(50% - 30px); // Adjust for gutters
    }</code>
  • Element Ordering:

    <code class="css">.content h2 { 
      order: 0; // Heading (row 1)
    }
    
    .content p { 
      order: 1; // Paragraphs (row 2)
    }
    
    .content p + p { 
      order: 2; // Second paragraph (row 3)
    }
    
    .content ul { 
      order: 3; // List (row 4)
    }</code>

Considerations:

  • Borders: To add borders, use a combination of border properties on the elements and adjust them with the media query to account for the different stacking configurations.

Updated Code:

See the updated codepen for a working example:

[Codepen Link]

The above is the detailed content of How to Align Vertical Content Horizontally in Flexbox Columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn