Auto-sizing width with fit-content in css

The code is working as it should. The parent div will only stretch its width up to the contents inside it, i.e the child div.

And here you have defined the width of child div as 100px, so the parent div width will also expand only till 100px, and about the text, which is overflowing outside child div, is not considered as content for parent div.

If you want the parent to fit the content of the children, you should change the width of child div to fit-content

like this

.parent {
  border: 1px solid red;
  width: fit-content;
}

.children {
  border: 1px solid green;
  width: fit-content;
}
<div class="parent">
  <div class="children">
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
  </div>
</div>

Ok, so I am not sure I totaly understand what you want to do but we can start from this answer. I dont't know how much you know about CSS so dont't be offended by my answer.

  • First, in HTML most elements have, by default, two types of rendering (this is really simplified) : block-level or inline. A block-level element will take the width of its parent. An inline element will take the width of its content.

  • So if you understand that principle you'll see that having the parent element to be as wide as its children which is as wide as its content is pretty simple. Here is an exemple:

.parent {
   border: 1px solid red;
   /* This will make the parent as wide as its content */
   display: inline-block;
}

.children {
   border: 1px solid green;
   /* This is just so that we see if it's working */
   max-width: 100px;
}
<div class="parent">
  <div class="children">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</div>

Now, of course there are other ways to do it, but this is the simplest solution. The best solution will depend on your context.

Tags:

Html

Css