Home > other >  How to align multiple flex boxes on top of each other?
How to align multiple flex boxes on top of each other?

Time:07-28

I have the following UI:

enter image description here

And the code for the UI looks like this:

            <% @list.each do |gift| %>
                <div style="display:flex; gap:120px; position:relative; right:150px; width:20px;"
                    <% item.each do |k,v|%>
                        <p> <%=v%> </p>
                    <% end %>
                </div>
            <% end %>

The parent div is a flex box meaning each row is a flex child. I set a gap for each flex item though and that ends up throwing each child element off balance since the length of text affects the gap. How can I make it so each flex item is aligned? Im assuming I would have to get rid of my use of gap

CodePudding user response:

you can specify how much space each item inside the flex takes, if you want to equally divide the flex then add flex: 1 for each item inside the flex, or if you want each one to take a specific space use flex-basis: 200px or change the value to anything you want.

in your case I belive this will solve your problem:

 <% @list.each do |gift| %>
    <div style="display:flex; gap:120px; position:relative; right:150px; width:20px;"
        <% item.each do |k,v|%>
            <p style="flex: 1"> <%=v%> </p>
        <% end %>
    </div>
<% end %>

CodePudding user response:

Hide the overflow to stop flexbox from growing when text doesn't fit, but also wrap overflowing text to keep it visible.

div {
  display: flex;
  gap: 5rem;
  width: 350px;
}

div p {
  border: 1px solid;
  flex: 1;
  overflow: hidden;
  overflow-wrap: break-word;
}
<div>
  <p> one </p>
  <p> two </p>
  <p> three </p>
</div>

<div>
  <p> oneone one one one one  </p>
  <p> twotwotwo two two two </p>
  <p> threethreethreethree three </p>
</div>

<div>
  <p> oneoneoneoneoneoneoneoneoneone </p>
  <p> twotwotwotwotwotwotwotwotwotwo </p>
  <p> threethreethreethreethreethreethree </p>
</div>

  • Related