skip to Main Content

I have an outer div with a fixed width, and an inner div. Inside the inner div can be a button with a fixed size or a div with width 100%.

Is there a way to have the inner div fit the button at its width, and fit the full width div at full width?

I tried various combinations of width, minWidth, maxWidth, some flex properties, but nothing seems to work.

<div style="width:500px">
  <div style="??">
    <button>Button</Button>
  </div>
</div>

and

<div style="width:500px">
  <div style="??">
    <div style="width:100%/>
  </div>
</div>

2

Answers


  1. Hmm you can achieve this layout using flexbox and a combination of min-width and max-width properties. Here’s how you can do it:

    <div style="width: 500px; border: 1px solid black;">
      <div style="display: flex;">
        <button style="min-width: 0; flex-grow: 1;">Button</button>
      </div>
    </div>
    
    <div style="width: 500px; border: 1px solid black; margin-top: 10px;">
      <div style="display: flex;">
        <div style="width: 100%; border: 1px solid blue;"></div>
      </div>
    </div>
    

    Let me explain what’s happening here:

    • For the button case:

      • We use display: flex; on the inner div to make it a flex container.
      • min-width: 0; on the button ensures that it can shrink beyond its
        intrinsic width to fit the container.
      • flex-grow: 1; makes the button occupy the remaining space within the
        flex container.
    • For the div case:

      • We use display: flex; on the inner div again.

      • Inside, the child div with width: 100%; will naturally expand to fill
        the available space, as it’s the only item in the flex container.

    This should give you the desired behavior where the button fits its width and the div expands to fill the available space.

    Login or Signup to reply.
  2. All you need is fit-content on that inner div:

    .outer {width: 500px; background: #f7f7f7; margin: 1em;}
    .outer > div {background: #e7e7e7; width: fit-content;}
    <div class="outer">
      <div>
        <button>Button</Button>
      </div>
    </div>
    
    <div class="outer">
      <div>
        <div>Some text in a div that is long enough to fill the container and wrap a bit.</div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search