Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set div to have its siblings width

Tags:

html

css

I'm looking for a CSS solution to the following:-

<div style="display:inline;">       <div>The content of this div is dynamically created but will always be wider than                the below div.        </div>       <div> Need this div to have the same width as the above div.       </div>  </div>

The wrapper div has an inline display and works as expected, both child divs have dynamically generated content. I need the bottom one to take the width of the previous sibling.

Many thanks for any suggestions in advance.

like image 671
user1278456 Avatar asked Mar 19 '12 11:03

user1278456


People also ask

How do I make a div stay the same size?

if you set width:500px; and height:300px; (or whatever size you want) the div should stay the same size. Also, you can set overflow:hidden; so that if whatever is in the div goes beyond those bounds, it is not shown, and does not resize the div. Show activity on this post. Try this one.

How do I make a div auto adjust width?

Set display to inline-block to make the div width fit to its content. Use position: relative and left: 50% to position its left edge to 50% of its containing element. Use transform: translateX(-50%) which will "shift" the element to the left by half its own width.

How do you make a div full width of a parent?

Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.

Is a div 100% width by default?

auto automatically computes the width such that the total width of the div fits the parent, but setting 100% will force the content alone to 100%, meaning the padding etc. will stick out of the div, making it larger than the parent. so setting the 'width' to 'auto' would be better? Yes, but that's the default anyway.


1 Answers

Here's another Flexbox solution which allows for the second child to wrap to match the width of the variable height sibling.

.wrapper > div {    border: 1px solid;  }    .child {    display: flex;  }    .child div {    flex-grow: 1;    width: 0;  }    .wrapper {    display: inline-block;  }
<div class="wrapper">      <div>This div is dynamically sized based on its content</div>      <div class="child"><div>This div will always be the same width as the preceding div, even if its content is longer (or shorter too).</div></div>  </div>

Edit:

To support multiple divs under .child, where each div is on its own line, add break-after: always; ...

.child div {   flex-grow: 1;   width: 0;   break-after: always; } 
like image 125
Peter Josling Avatar answered Sep 28 '22 06:09

Peter Josling