2

EDIT: It turns out this is currently impossible with just CSS. A good explanation can be found here: CSS Width / Max-Width on Line Wrap?


Below, I have an outer class which specifies a fixed width, and an inner class which contains text.

<div class="outer">
  <div class="inner">
    Lorem ipsum dolor sit, consectetur adipiscing elit, sed do eiusmod tempor
  </div>
</div>
.inner {
  padding: 0.25rem;
  border: 1px solid grey;
}

.outer {
  width: 12.5rem;
  padding: 0.25rem;
  border: 1px solid lightblue;
}

This leaves a gap to the right of the text:

A: enter image description here

But I would like the inner class to wrap tightly to the text itself, like this:

B: enter image description here

How can I achieve B using CSS?

I need a solution that is more dynamic than specifying an exact width for inner and doesn't change where the line breaks occur (e.g. using word-wrap: break-all)!


Clarification

The padding is there just to help make the example look clearer. Without padding, the issue remains.

I get:

But I would like:

Bret Cameron
  • 451
  • 1
  • 4
  • 18
  • In your `.outer` container you have the same padding at all sides. Why don't you use a bigger padding to the right? – Azu Nov 16 '22 at 11:42
  • That would create extra space between the blue and grey borders, but without making the grey border tightly wrap the text. – Bret Cameron Nov 16 '22 at 11:45
  • This is because you have `padding` to the right in the `inner` container. So try to put `padding-right: 0.5rem` to `outer` and `padding-right: 0` to `inner`. – Azu Nov 16 '22 at 11:53
  • I have added some clarification about padding to the original question. – Bret Cameron Nov 16 '22 at 12:34

1 Answers1

0

    .inner {
  padding: 0.25rem 0 0.25rem 0.25rem;
border: 1px solid grey;
word-break: break-all;
}

.outer {
  width: 12.5rem;
padding: 0.25rem 1.5rem 0.25rem 0.25rem;
border: 1px solid lightblue;
}
<div class="outer">
  <div class="inner">
    Lorem ipsum dolor sit, consectetur adipiscing elit, sed do eiusmod tempor
  </div>
</div>
Azu
  • 1,494
  • 2
  • 6
  • 11
  • Thanks. This is closer to what I'm aiming for, but I'm looking for a solution which doesn't change where the line breaks occur. – Bret Cameron Nov 16 '22 at 12:06