开发者

width and height for a span does not show up unless a text is entered

开发者 https://www.devze.com 2023-01-07 16:57 出处:网络
I have a <span id=\"some\"></span> and the css is #some{ background-color:#000; width:150px; height:50px;

I have a <span id="some"></span> and the css is

#some{
      background-color:#000; width:150px; height:50px; 
}

The width and height does not show unless something is entered.开发者_StackOverflow How can i fix this?


span is an inline element, so without telling browser that its display property as block what you do won't work out.

So in brief:

#some{
  background-color:#000; 
  width:150px; 
  height:50px; 
  display: block;
}

Hope it helps, Sinan


You can't give a height/width to an inline element, it's sized by it's content, but you can give it display: inline-block; like this:

#some{
  background-color:#000; width:150px; height:50px; display: inline-block;
}​

See an example here, note that IE7 in particular won't handle this in some situations, so display: block; would work there (but honestly, why not just use a <div> then?)...but keep in mind inline-block is in the flow, whereas block kicks everything down a line.


One can make span width and height working even without setting display as block by setting position value as absolute to it.

.green-box{
      background-color:gold; 
      position:absolute;
      width:300px;
      height:100px;
      border: 2px solid silver;
}

Checkout this link for more := https://jsfiddle.net/vipingoyal1000/oa2ssb19/


A common solution is using &nbsp; in the span tag. (I'm assuming you want to make it display:block; as well?)


As everyone else mentioned span is inline element, you either need to make it block element (using display:block) or to use block element (div) in its place. In order to better understand inline and block elements, as well the whole html/css rendering model, I suggest you read http://www.w3.org/TR/CSS2/visuren.html.


Using display:block; it will work perfectly.

Thanks Rex

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号