2

I have a question on nested spans and how CSS applies the width attribute. The HTML is like this, the 'wide' class sets the width. The box class gives it a border. Width gets applied only if I have wide and box together. Can someone explain to me why this is the case? I am CSS amateur, maybe this is some basic rule that I missed.

<span class="wide"><span  class="box">Not wide</span></span>
<span class="wide box"><span>Wide</span></span>
<span><span class="wide box">Wide</span></span>
<span class="box"><span class="wide">Not wide</span></span>

You can see the effect here: http://jsfiddle.net/7hXUu/2/

Thanks for any insight, Aaron

Aaron Newman
  • 549
  • 1
  • 5
  • 27
  • [a possible answer](http://stackoverflow.com/questions/2491068/does-height-and-width-not-apply-to-span) – Vidul Aug 14 '12 at 08:09

3 Answers3

1

The reason is using float:left;. But i don't know what exactly cuases this.

You may apply the width for elements like span, a by using display:block; or display:inline-block;

Alaa Badran
  • 1,848
  • 15
  • 19
  • 1
    You guys are fast, thanks! Adding display:block; to wide class fixes last case, adding 'width:inherit' to box class fixes first case. – Aaron Newman Aug 14 '12 at 08:18
1

Widths cannot be applied to inline elements, however rendering behaviour is different for floated inline elements:

If 'width' is computed as 'auto', the used value is the "shrink-to-fit" width... Then the shrink-to-fit width is: min(max(preferred minimum width, available width), preferred width)

That's not all. Your floating container spans each establish new block formatting contexts, affecting the calculated results of floated element positioning. I could probably go over it step-by step if there were enough requests, but this is definitely an unpractical scenario.

Bottom line is: this is good spaghetti code for a brain-teaser question, but horrible for real-life use.

Oleg
  • 24,465
  • 8
  • 61
  • 91
-1

The box class has float: left, turning the element to a floated element, as opposite to the default for span, an inline element. The width property does not apply to inline elements.

Another way of making width apply to a span element is to set display: inline-block on it.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390