开发者

How do I prevent floated-right content from overlapping main content?

I have the following HTML:

<td class='a'>
  <img src='/images/some_icon.png' alt='Some Icon' />
  <span>Some content that's waaaaaaaaay too long to fit in the allotted space, but which can get cut off.</span>
</td>

It should display as follows:

[Some content that's wa [ICON]]

I have the following CSS:

td.a span {
  overflow: hidden;
  white-space: nowrap;
  z-index: 1;
}

td.a img {
  display: block;
  float: right;
  z-index: 2;
}

When I resize the browser to cut off the text, it cuts off at the edge of the <td> rather than before the <img>, which leaves the <img> overlapping the <span> content. I've tried various padding and margins, but nothing seemed to work. Is开发者_JS百科 this possible?

NB: It's very difficult to add a <td> that just contains the <img> here. If it were easy, I'd just do that :)


It's possible that overflow: hidden isn't working because you are applying it to an inline element.

One solution might be to place that span inside a div, giving that div overflow: hidden. Or change the span to a div. You may still need to mess around with giving the div a right margin the width of the image.

It would be a lot easier without the white-space: nowrap property. Is there any possible way you could re-design your application so it doesn't need to use this?


Give this a try:

td.a {
   position: relative;
}

td.a span {       
   display: block;
   overflow: hidden;
   white-space: nowrap; 

   position: relative;
   z-index: 1;

   padding-right: 20px; /* This should be the width of your image */
}

td.a img {
   position: absolute;
   z-index: 2;
   top: 0;
   right: 0;       
}

It will put the image to the far right of your <td> and the right padding on the <span> will keep the image from overlapping the text.

The reason for the position: relative in the <td class="a"> is so that it becomes the coordinate system for the position: absolute <img>. You also need a position type (relative, absolute or fixed) for z-index to work.

If that doesn't work, would it be an option to put the image as a background image on the <span> like so:

td.a span {       
   display: block;
   overflow: hidden;
   white-space: nowrap; 

   padding-right: 20px; /* This should be the width of your image */
   background: url(your-img.png) no-repeat 100% 0; /* right-top aligned background */
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜