Nick Nick - 1 year ago 134
CSS Question

CSS to stop text wrapping under image

I have the following markup:

<li id="CN2787">
<img class="fav_star" src="images/fav.png">
<span>Text, text and more text</span>
</li>


I want it so that if the text wraps, it doesn't go into the 'column' for the image. I know I can do it with a
table
(which I was doing) but this is not workable for this reason.

I've tried the following without success:

li span {width: 100px; margin-left: 20px}
.fav_star {width: 20px}


I also tried
float: right
.

Thanks.

EDIT: I want it to look like this:

IMG Text starts here and keeps going... and
wrap starts here.


Not like this:

IMG Text starts here and keeps going... and
wrap starts in the space left for the image.

Dan Dan
Answer Source

Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:

This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.

The span element is an inline element, you can't change its width in CSS.

You can add the following CSS to your span so you will be able to change its width.

display: block;

Another way, which usually makes more sense, is to use a <p> element as a parent for your <span>.

<li id="CN2787">
  <img class="fav_star" src="images/fav.png">
  <p>
     <span>Text, text and more text</span>
  </p>
</li>

Since <p> is a block element, you can set its width using CSS, without having to change anything.

But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.

li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}

P.S. Instead of float:left on the image, you can also put float:right on li p but in that case, you will also need text-align:left to realign the text correctly.

P.S.S. If you went ahead with the first solution of not adding a <p> element, your CSS should look like so:

li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download