21

Is it possible to maintain the width of a span somehow if it is empty?

I have the following HTML pseudo table:

<p><span class="col1">Day:</span><span class="col2"><?php echo somephp ?></span></p>
<p><span class="col1">Time:</span><span class="col2"><?php echo somephp ?></span></p>
<p><span class="col1">Class:</span><span class="col2"><?php echo somephp ?></span></p>
<p><span class="col1">Teacher:</span><span class="col2"><?php echo somephp ?></span></p>

With CSS:

span.col1 {width: 100px;float: left;}
span.col2 {width: 100px;}

Sometimes the PHP that is echoed in col2 is empty and when this happens col2's width is 0 and col1 on the paragraph below it ends up stacking up next to col1 in the paragraph above.

user1444027
  • 4,983
  • 7
  • 29
  • 39

3 Answers3

48

Your col2 spans are ignoring the width because they are inline elements. You need to make them inline-block elements.

span.col2 { width: 100px; display: inline-block }

Also keep in mind that you may need to add a height to it depending on where it's displayed, or you'll end up with a span 100px wide but 0px high.

animuson
  • 53,861
  • 28
  • 137
  • 147
4

By default span displays as inline.

So either add display:block to give it a block element or additionally you could use display:inline-block to keep it inline with the rest of the text (without using float).

Andy
  • 1,123
  • 6
  • 9
2

By default span element is an inline element, and it ignores width.

Try adding display:block to your spans.

span.col1 {width: 100px;float: left; display:block;}
span.col2 {width: 100px; display:block;}

Hope it helps.

Marko Francekovic
  • 1,450
  • 10
  • 10
  • 2
    `display:block;` adds a line break. – prageeth Nov 04 '12 at 23:15
  • That is correct, but question was how to have spans maintain width with empty content. And I have suggested using block because older browsers IE8- don't work with inline-block. – Marko Francekovic Nov 04 '12 at 23:20
  • 1
    Older browsers typically don't work with inline-block if by default the element is displayed as a block. However, if the element is natively inline, e.g. `span` then it will work fine. – Andy Nov 04 '12 at 23:22