How to Vertically Align Elements from Different Parents in CSS without JavaScript?

Patricia Arquette
Release: 2024-10-23 17:58:29
Original
638 people have browsed it

How to Vertically Align Elements from Different Parents in CSS without JavaScript?

CSS - How to Align Children in Different Parents Vertically

To align children in different parents vertically without using JavaScript, make them siblings and use flexbox to control their order and flex basis. Here's how to achieve this:

Updated Code:

<code class="css">@media (min-width: 768px) {
  .content {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
  }

  .content > * {
    flex-basis: calc(50% - 30px);
  }

  .content h2 {
    order: 0;
  }
  .content p {
    order: 1;
  }
  .content p + p {
    order: 2;
    flex-basis: calc(100% - 30px);
  }
  .content ul {
    order: 3;
  }
}</code>
Copy after login

HTML Code:

<code class="html"><div class="content">
  <h2>Lorem ipsum Lorem ipsum</h2>
  <p>...</p>
  <p>...</p>
  <ul class="check">...</ul>
  <h2>Lorem ipsum</h2>
  <p>...</p>
  <ul class="check">...</ul>
</div></code>
Copy after login

Explanation:

  • On screens wider than 768px, the content is displayed as flex items, with their order determined by order properties.
  • flex-basis sets the width of each item, but a 100% width is set for the empty p element to ensure it fills the available space.
  • By making the elements siblings within the content div, they are able to align vertically.
  • Customize the breakpoints in the media query to match Bootstrap's if needed.
  • You can also add borders to the elements using border properties, adjusting them with the media queries to support both vertical and horizontal alignment.

The above is the detailed content of How to Vertically Align Elements from Different Parents in CSS without JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!