Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Joe Consterdine
Joe Consterdine
13,965 Points

Why Doesn't a Span collapse with text inside it once it goes to a new line?

Hey guys,

so when you put an image inside a span element it doesn't respect the images width/height as it's inline.

When you add a bunch of text inside a span it wraps and respects the text and has a height.

for e.g if I did this:

<span><img src="image.jpg"></span>

The span would have no height.

If I did this:

<span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.</span>

The span would respect the text and have a height.

Why is this?

I thought that it would be because anything with a width/height doesn't get respected as it's inline.

But if you do this:

<span><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.

Donec nec justo eget felis facilisis fermentum. Aliquam porttitor mauris sit amet orci. Aenean dignissim pellentesque felis.</p></span>

And now wrap the text in a p tag which is block then the span collapses again.

This doesn't hinder me but I was just wondering how it worked.

Cheers.

Joe

1 Answer

Jason DeValadares
Jason DeValadares
7,190 Points

Text has a defined height based on default CSS rules built into every browser. Since you're not telling it what the new attribute height or width is - it has no idea. Spans are inline elements, not block elements. I haven't tested this, but I bet if you did this in the CSS first, it would then block out that needed space in the span

img {
   width:100px;
   height:100px;
}