Reputation:
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>
Upvotes: 4
Views: 233
Reputation: 372244
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
Upvotes: 0
Reputation: 592
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.
Upvotes: -1
Reputation: 274384
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>
Upvotes: 2