0

How do I get a text element, for example <p> to dynamically be exactly the same width as the text? If the text is forced to new rows by a parent or the document width.

You can see the problem illustrated here:

.wrapper {
  background-color:#ff0000;
  padding:10px;
  width:530px;
}
p {
  background-color:#00ff00;
  display:inline-block;
  width:auto;
}
<div class="wrapper">
  <p>This sentance wants to be alone on it's row.</p>

  <p>Now we want this element to be as narrow as possible. Removing this space: before-this-word.</p>
</div>

I have tried to find answers for this, but can't find any.

Peter Westerlund
  • 741
  • 1
  • 10
  • 36

2 Answers2

1

Give display: initial or inline instead of inline-block;

.wrapper {
  background-color:#ff0000;
  padding:10px;
  width:530px;
}
p {
  background-color:#00ff00;
  display: initial; /*or  display: inline; */
  width:auto;
}
<div class="wrapper">
  <p>This sentance wants to be alone on it's row.</p>
  <br/>
  <p>Now we want this element to be as narrow as possible. Removing this space: before-this-word.</p>
</div>
Deepu Reghunath
  • 8,132
  • 2
  • 38
  • 47
  • 1
    note that `initial` of display is `inline` – Temani Afif Sep 04 '19 at 15:46
  • 1
    a `p` is a block level element, `initial` would result in it acting as if it was a block level element again. – Adrian Roworth Sep 04 '19 at 16:01
  • @AdrianRoworth no, this is false. Initial means inline and doesn't mean the *initial* display set by the browser. So even for `p` or `div` it will be `inline` – Temani Afif Sep 04 '19 at 18:36
  • @TemaniAfif https://developer.mozilla.org/en-US/docs/Web/CSS/initial_value. `The initial value of a CSS property is its default value, as listed in its definition table` – Adrian Roworth Sep 05 '19 at 13:28
  • @AdrianRoworth and you know what is the *definition table*? check this link: https://developer.mozilla.org/en-US/docs/Web/CSS/display#Specifications it's at the bottom of Spec list where you will see `Initial value inline` (by the way it is already clear from the example that `p` is behaving as inline here not as block) – Temani Afif Sep 05 '19 at 13:30
  • @TemaniAfif cheers for the heads up! I read this part of the definition: `The initial value of a CSS property is its default value` and because a `

    ` is a block level element assumed `default` meant `block`. This could be far clearer by just explicitly saying what you are saying! :D

    – Adrian Roworth Sep 06 '19 at 09:43
0

Add white-space: nowrap; to your css, Any element with white-space: nowrap stays on one line

.wrapper {
  background-color:#ff0000;
  padding:10px;
  width:auto;
}
p {
  background-color:#00ff00;
  display:inline-block;
  width:auto;
  white-space: nowrap;
}
<div class="wrapper">
  <p>This sentance wants to be alone on it's row.</p>

  <p>Now we want this element to be as narrow as possible. Removing this space: before-this-word.</p>
</div>
AutoTester213
  • 2,714
  • 2
  • 24
  • 48