0

HTML:

 <div id='container'>
  <p>This is some text contained within a small-ish box. I'm using it as an example of how placing your floated elements in different orders in your HTML can affect your layouts. For example, take a look at this great photo placeholder that should be sitting on the right.</p>
 <img src='image.gif'>
 </div>

CSS:

#container {
    width: 280px;
    margin: 0 auto;
    padding: 10px;
    background-color: #aaa;
    border: 1px solid #999;
}

p {
    width: 100px;
}

img {
    float: right;
}

Result: https://jsfiddle.net/y9Lqjm1f/

Why if the paragraph's width is small enough does the floated right element not appear at the top of the container div?

Robert
  • 10,126
  • 19
  • 78
  • 130
  • I'm not sure the answer to your question exactly, but I was just playing with your fiddle and noticed that if you add `display: inline-block` to the paragraph styling and make the paragraph's width small enough, the image will appear at the top of the container div. – Robert Hickman Mar 13 '16 at 02:29
  • Float first - http://alistapart.com/article/css-floats-101#section5 – Stickers Mar 13 '16 at 02:38

2 Answers2

1

Because the img element is placed below the p element which follows the normal flow as a block element.

img's separate flow, which results from it having a float style applied, only begins below the p.

If you added another p below the img it would follow normal layout flow as if the img did not exist, like so: https://jsfiddle.net/mkarajohn/y9Lqjm1f/1/

In short, in order for the img to appear to the top, it has to be placed first in the markup, like so: https://jsfiddle.net/mkarajohn/y9Lqjm1f/2/

Also see this about float and block elements

In general:

  • Floated elements respect previous block elements' layout flow, meaning they appear below the previous block element
  • Block elements following the floated element disregard the floated element, and keep their normal layout flow as if the floated element did not exist.
Community
  • 1
  • 1
Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63
0

p and img tags are block level elements. They create new line for next element. So, float: right; property in img apply in new line.

You can use display: inline-block; for both p and img tags.

codepen