2

I have the following html code:

<p>some text</p>
<img src="#" alt="image" width="200" height="250" />

I want to pull the text to the right of the image.

I can't find anywhere how to do this with regular CSS without changing the order of the html code.

I tried to use float:left on the image but that's only affecting html elements after the image.

What's the right approach?

To be more clear, right now I am getting this:

some text
_____________
|           |
|   image   |
|           |
|___________|

What I want is this:

_____________
|           | some text
|   image   |
|           |
|___________|
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Kolja
  • 860
  • 4
  • 10
  • 30
  • 2
    Why would you not just place the `` before the`

    `? Since you want it rendered before the text, it seems like it would make more sense to place it before the text.

    – kittykittybangbang Aug 16 '15 at 01:25

2 Answers2

4

There is a simple way to re-arrange the visual order of elements with CSS Flexbox.

No changes to the HTML.

The flex order property is designed to re-arrange elements within the flex container.

enter image description here

#container {
  display: flex;
  border: 2px solid black;
  background-color: lightgray;
}
p {
  order: 1;
}
img {
  margin: 10px;
}
<div id="container">
  <p>some text</p>
  <img src="http://i.imgur.com/60PVLis.png" alt="image" width="75" height="75">
</div>

In the example above, child elements of the flex container (#container) are aligned in a row, which is a default setting (flex-direction: row).

The default value of the order property is 0, which means that elements will align in the order they appear in the source.

By giving the p an order: 1, it jumps ahead of elements with order: 0.

Alternatively, we could give the image an order: -1, putting it before the text.

Learn more about the order property here.

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
2

Switch up the order

<img src="#" alt="image" width="200" height="250" />
<p>some text</p>

then float both the img and the p left

img, p {
    float: left;
}

OR

Keep the order and float both right:

img, p {
    float: right;
}

You will probably need to adjust the width of the element which contains these 2 elements, since it will float it to the far right side of it.

dangor
  • 455
  • 3
  • 10