oldboy
oldboy

Reputation: 5954

Prevent child from assuming full width of dynamic width parent

I have a container, and the width of this container is determined by either max-width or the width of its widest child.

enter image description here

How do I force each child to assume the width of its content while maintaining a single column of elements?

In the example below, how do I make the abc elements, outlined by the limegreen border, only as wide as their content (i.e. abc)?

#container {
  display: inline-block;
box-sizing: border-box;
border: solid orange 2px;
}

.child {
box-sizing: border-box;
border: solid limegreen 2px;
}
<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>

Upvotes: 2

Views: 1156

Answers (2)

Aleksandr Belugin
Aleksandr Belugin

Reputation: 2227

Made .child width: fit-content;

#container {
  display: inline-block;
  box-sizing: border-box;
  border: solid orange 2px;
  direction: rtl;
}

.child {
  box-sizing: border-box;
  border: solid limegreen 2px;
  width: fit-content;
}
<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272955

a flexbox layout will do the job

#container {
  display: inline-flex;
  flex-direction: column;
  align-items:flex-start; /* OR flex-end */
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
}
<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>

Or display:table :

#container {
  display: inline-block;
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
  display:table;
  /* margin-left:auto to push to the right */
}
<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>

Even float will do the job:

#container {
  display: inline-block;
  border: solid orange 2px;
}

.child {
  border: solid limegreen 2px;
  float:left;
  clear:left;
  /* OR right for both */
}
<div id='container'>
  <div class='child'>abcdefghi</div>
  <div class='child'>abc</div>
  <div class='child'>abc</div>
</div>

Upvotes: 3

Related Questions