4

Someone here recommend me to use display:inline-block to make the width of the element be the same as its content. So I tried, but doing so, I ended up with the text getting all mixed. How do I fix this?

The second pair is what I wanted, but with the width of the Paragraph extending only as its content.

<p style="display: inline-block">Inline-block P</p><span>Normal span</span>
<p>Normal P</p><span>Normal span</span>
  • 2
    `The second pair is what I wanted` so ? you have what you wanted .. and why you want the width to extend content and also a line break ? simply keep the default behavior – Temani Afif Jan 29 '18 at 22:59
  • keep the inline tag and add a ``
    `` tag where yo want the text to break
    – Gerardo BLANCO Jan 29 '18 at 23:02

3 Answers3

2

Your title say Unexpected behavior but this is the normal behavior. You made your element to behave like an inline element so there is no more line break and thus you will have this behavior.

If you want the p to have only the width of its content AND to have line break simply wrap it inside a div (a block element):

<div>
  <p style="display: inline-block;background:red;">Inline-block P</p>
</div>
<span>Normal span</span>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
0

You've set your elements to inline-block, which makes them inline-level, which places them on the same line.

Here's an alternative: Use an inline-level flex container, like this:

body {
  display: inline-flex;
  flex-direction: column;
}

body > * {
  border: 1px dashed red;
}
<p>Inline-block P</p>
<span>Normal span</span>
<p>Normal P</p>
<span>Normal span</span>

More info: Make flex container take width of content, not width 100%


Or use a block-level flex container, but override the default stretch value on align-items:

body {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

body > * {
  border: 1px dashed red;
}
<p>Inline-block P</p>
<span>Normal span</span>
<p>Normal P</p>
<span>Normal span</span>

More info: Make flex items take content width, not width of parent container

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
-1

Make your span display = block.

HTML:

<div id=container>
   <p>Hello, world!</p><span>Here is my span</span>
</div>

CSS:

* {
   margin: 5px;
   padding: 5px;
}
div {
   background: gray;
}
p {
   background:white;
   border-bottom: 1px dotted black;
   display: inline-block;
}
span {
  display: block;
}

Here is a fiddle.

Jeff Matthews
  • 602
  • 2
  • 7
  • 17