Home  >  Article  >  Web Front-end  >  How to Maintain Alignment in Responsive Rows Without JavaScript

How to Maintain Alignment in Responsive Rows Without JavaScript

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 16:57:01934browse

How to Maintain Alignment in Responsive Rows Without JavaScript

Maintaining Heights of Siblings in Responsive Rows

When faced with columns containing varying content lengths and a desire to maintain alignment within them, using JavaScript isn't necessary. By modifying CSS, we can create flexible layouts that meet the desired functionality without breaking mobile optimizations.

The key is to make the items in each column direct siblings, so they can "see" each other. Then, we use media queries to rearrange their order based on screen width. This ensures that on wider screens, the items are side-by-side, while on narrower screens, they stack vertically.

Updated Code:

To achieve this, we introduce a content class that wraps all the elements within each column:

<code class="css">.content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}</code>

Individual elements within the content are given a custom width:

<code class="css">.content > * {
  flex-basis: calc(50% - 30px);
}</code>

Media Query:

For wider screens, we use a media query to reorder the elements and adjust their widths:

<code class="css">@media (min-width: 768px) {
  .content h2 {
    /*  1st row  */
    order: 0;
  }

  .content p {
    /*  2nd row  */
    order: 1;
  }

  .content p + p {
    /*  3rd row  */
    order: 2;
    flex-basis: calc(100% - 30px);
  }

  .content ul {
    /*  4th row  */
    order: 3;
  }
}</code>

Additional Notes:

  • You may need to adjust the media query breakpoint and flex-basis values for different screen sizes.
  • To account for elements differing in height, you can apply border properties to individual elements with additional media queries.

The above is the detailed content of How to Maintain Alignment in Responsive Rows Without JavaScript. 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