user3494047
user3494047

Reputation: 1693

Make ancestor flexbox divs only take up the width of its child with a set width

I have an input element using flex display and I set its flex-basis width like so:

.flex-row input { flex: 0 1 450px; }

and a flex-row div is contained inside of a flex-container div.

I want the flex-row to only take up the width that the input takes.

When I give flex-container display: flex it takes up 100% width.

When I give it display: inline-flex it compresses the input making it much smaller than 450px.

I don't really care about the width of flex-container, although it would be nice for it to take up the width of its child as well, but how do I make flex-row have the same width as the input (namely, when there is enough room for it, 450px)?

.flex-container {
  display: flex;
}
.flex-row {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
}
.flex-row input {
  flex: 0 1 450px;
}
<div class="flex-container">
  <div class="flex-row">
    <input type="text" name="query" class="searchbar" />
  </div>
</div>

and here is a fiddle example.

Upvotes: 2

Views: 145

Answers (1)

Nasir T
Nasir T

Reputation: 2643

Add the same flex property to the flex-row as you have on the flex-row input.

.flex-row{
    display: flex;
    flex: 0 1 450px;
    align-items: center;
    justify-content: center;
}

If you want the row to be centered as well then add the align and justify properties to the flex-container as follows.

.flex-container{
   display: flex;
   align-items: center;
   justify-content: center;
}

Upvotes: 1

Related Questions