Fez Vrasta
Fez Vrasta

Reputation: 14835

Make child div fit its content while its parent has scrollbars?

I need to make the .child div wide as its content, but at the same time, the .child div is child of an element with horizontal scrollbars.

Is there a way without have to use fit-content (fit/min/max) and without javascript?

Demo: http://codepen.io/FezVrasta/pen/ZQOjZj

I've this CSS:

.parent
  width: 100px
  overflow: auto
  background: yellow

  .child
    background: cyan
    height: 20px
    white-space: nowrap

Upvotes: 2

Views: 298

Answers (2)

Jacob G
Jacob G

Reputation: 14172

Just display .child inline-block:

(Stylus)

  .child
    background: cyan
    height: 20px
    white-space: nowrap
    display:inline-block;

(Compiled)

.parent .child {
  background: #0ff;
  height: 20px;
  white-space: nowrap;
  display: inline-block;
}

Inline and inline-block elements shrink to fit their content, unless a width or height is set.

Updated Codepen

Or, a working snippet:

.parent {
  width: 100px;
  overflow: auto;
  background: #ff0;
}
.parent .child {
  background: #0ff;
  height: 20px;
  white-space: nowrap;
  display: inline-block;
}
<div class="parent">
  <div class="child">child child child child</div>
</div>

Upvotes: 3

Josh Crozier
Josh Crozier

Reputation: 240938

The reason this is occurring is because the .child element is a block-level element with a default width of 100%. This results in the .child element having the same width as the parent element.

You could add display: inline-block to the .child element. In doing so, it will have a "shrink-to-fit" width and take the width dimensions of the text.

Updated Example

.parent .child {
    background: #0ff;
    height: 20px;
    white-space: nowrap;
    display: inline-block;
}

Alternatively, setting the display to table would have a similar affect as well.

Updated Example

.parent .child {
    background: #0ff;
    height: 20px;
    white-space: nowrap;
    display: table;
}

Upvotes: 1

Related Questions