5

I'd like to make a div that will inherit its child width.

It works when child has only one line, but when it becomes multiline, the parent gets width of max-width property.

HTML:

<div class="message-content">
    <span>Lorem ipsumdolor ipsum dolorsit ametipsumdolor ipsum dolor sit amet ipsumdolor ipsum dolor sit amet</span>
</div>

SCSS:

.message-content {
    max-width: 450px;
    background: green;
    padding: 15px;
    border-radius: 3px;
    display: inline-block;
    span {
       background:red;
    }
}

Jsfiddle: https://jsfiddle.net/q0axyfp3/

Expected result: enter image description here

EDIT Here's the comparison of what I'm trying to achieve (in a responsive and elegant way of course): https://jsfiddle.net/q0axyfp3/5/

Does anyone know how to fix it?

Thank you very much

squidy06
  • 201
  • 2
  • 8
  • Your "CSS" is Less or SCSS; not actually CSS. – connexo Jan 26 '17 at 14:43
  • Actually I don't get what it is you want. To me it seems you're already there. – connexo Jan 26 '17 at 14:45
  • This is a little confusing.Do you want `message-content` to be the same width as `span`? – Matt Spinks Jan 26 '17 at 14:46
  • @MattSpinks Exactly (excluding padding) – squidy06 Jan 26 '17 at 14:51
  • _Inherit_ from a child? If I understood you correctly, you just need `display: block` in the `span`. Also that nesting in CSS is not valid. – Gabriel Jan 26 '17 at 14:59
  • @Gabriel CSS was a typo, fixed. But if I change span to be block element, then it'll behave exactly as parent div and gets more width than it's needed. Please compare expected result to JSfiddle's. – squidy06 Jan 26 '17 at 15:03
  • @squidy06 - Still a little confusing. `span` does not have a width. How do you want the parent div to be the same width of something that does not have a width? Why not just set a width on `span` and set the display to `block`? – Matt Spinks Jan 26 '17 at 15:07
  • Here's what I'm trying to achieve (in a responsive way of course): https://jsfiddle.net/q0axyfp3/5/ – squidy06 Jan 26 '17 at 15:12
  • 1
    If I understand your requirement correctly... **you can't** that's not the way the line box model works. See http://stackoverflow.com/questions/34995740/css-when-inline-block-elements-line-break-parent-wrapper-does-not-fit-new-width – Paulie_D Jan 26 '17 at 15:49
  • possible duplicate: [**Make container shrink-to-fit child elements as they wrap**](http://stackoverflow.com/q/37406353/3597276) – Michael Benjamin Jan 26 '17 at 15:50
  • @Paulie_D thank you :) – squidy06 Jan 26 '17 at 16:05
  • Does this answer your question? [How to resize the width of a div if a word wrap happened?](https://stackoverflow.com/questions/40643678/how-to-resize-the-width-of-a-div-if-a-word-wrap-happened) – mfluehr Dec 22 '22 at 16:45

1 Answers1

0

Give it a wrapper element written in html. Then set the width of both div's at 100%. Set the wrapper element to have a max-width of whatever you like.

DraganAscii
  • 322
  • 1
  • 9