skip to Main Content

I’m working on an HTML/CSS layout and facing an alignment challenge. I have a element, and within it, I want to position two child elements. Specifically, I need one child element to be aligned to the left edge of the div, and the other child element to be aligned to the right edge of the div. This is straightforward when there’s enough space.

However, the tricky part is that when the left element expands and occupies the entire width of the div, I want the right element to become centered within the remaining space. How can I achieve this dynamic alignment behavior using HTML and CSS?

I do not mind adding more <div>s or otherwise.

Diagram demonstrating intended behaviour:

Diagram demonstrating intended behaviour

I’ve attempted to solve this issue using Flexbox with justify-content: space-between. This approach allows me to position the two elements on either side of the container and even handle wrapping, but it causes problems when the left element expands, attempts to apply margin or other alignment tools to the element affects both before and after the expanse.

I also experimented with using a regular div and applying margin-left: auto to the right element, which did successfully push it to the right side. However, again I encountered difficulties in achieving the desired centering behaviour after wrapping.

2

Answers


  1. Try applying Flex-wrap:wrap to parent container

    Login or Signup to reply.
  2. to use flex, you have to start from 2 children where one takes the all free area and the second set to margin auto and a fleex parent than can wrap

    On a single line, the first one using all space avalaible will push the second to the end of the line.

    Once the first element grows bigger, it can push the second to next line, where margin:auto can fully express itself 🙂

    To reproduce your visual, the first element should not be seen and be just a container. It can also be a flex container to make things easier.

    example

    section {
      border: solid;
      padding: 1em;
      display: flex;
      flex-wrap: wrap;
      gap: 1em 0;
    }
    
    .flex-1 {
      flex: 1 0 auto;
      display: flex;
      max-width: 100%;
    }
    
    .green {
      border: solid;
      color: green;
    }
    
    .blue {
      border: solid;
      color: blue;
      margin: auto;
    }
    
    .green:hover:after {
      content: " Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.";
      color: red
    }
    <section>
      <div class="flex-1">
        <p class="green">Hover me to make me grow. </p>
      </div>
      <p class="blue">next to show</p>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search