9

I have a box with an image and some txt and I want the txt to be horizontal to the image. I know this may be a pretty easy question but I can't seem to find a good answer on the interwebs. thanks for any help.

<div id='container'>
 <img src='someimage.jpg'/>
 <p>some text</p>
</div>
JamesTBennett
  • 2,091
  • 6
  • 19
  • 22

3 Answers3

24

Take a look at CSS's float property, for example:

<div id='container'>
 <img src='someimage.jpg' style='float: left;'/>
 <p>some text (that will now wrap around the image</p>
</div>
Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
  • 3
    Yeah I've done this but what doesn't make sense to me is the paragraph goes threw the image. Like if I add padding the padding is against the container not the img. Also the margin of the paragraph affects the img and both are pushed away from the top of the container. – JamesTBennett Jun 24 '10 at 20:10
  • Surely you'd want a margin on the image? – Rowland Shaw Jun 24 '10 at 22:20
  • Not in this care. I've been wondering is it bad practice to just set things to postion:"absolute" and then just give them x y cords using top and bottom? – JamesTBennett Jun 26 '10 at 20:03
0

Since Rowland's 2010 answer, CSS has come a long way. Today we have Flexbox which is a part of CSS for controlling layout of elements in a row or column. It has a great deal of flexibility for handling alignment within the box and expanding or shrinking elements to fit.

Here is a simple example of how to style the HTML you provided (with the image URL changed to one that will render here).

#container {
    display: flex;
    align-items: center;
}

#container p {
    margin-left: 1em;
}
<div id='container'>
  <img src='http://placekitten.com/100/100' alt="" />
  <p>some text</p>
</div>

The MDN tutorial linked above is a good place to learn more.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-2

I recommend you to put the text and the image in a table, in the same row, the image would be in the first column, while the text goes to the second column in the first row . here's the code

<div id='container'>
  <table>
    <tr>
     <td><img src='someimage.jpg'/></td>
     <td><p>some text</p></td>
    </tr>
  </table>
</div>
  • 1
    Using a table for this sort of layout hack hasn't been needed since 1996 when CSS 1 came out. Today, flexbox is generally the best option. – Quentin May 03 '22 at 15:12