Mariadicar
Mariadicar

Reputation: 41

Top in position relative is not working as expected

Why doesn't work top attribute for <img> , when the tag <img> is sibling to <p>, but if I delete tag <p>, this works.

html,
body {
  height: 100%;
}

img {
  position: relative;
  top: 40%;
}
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus delectus accusantium nulla eveniet aperiam, quo odit qui voluptas. Illo vel sed ex dolores illum eum architecto a libero atque. Voluptatibus.</p>
<img src="http://lorempixel.com/400/200/" alt="">

Upvotes: 4

Views: 7868

Answers (5)

&#214;m&#252;rcan Cengiz
&#214;m&#252;rcan Cengiz

Reputation: 2159

When the value is provided as a percentage, it is relative to the height of the containing block.

But img has no containing block. You can add position: absolute; to the img.

CSS:

img{
    position: absolute;
    top: 40%;
}

Upvotes: 1

Marcel Burkhard
Marcel Burkhard

Reputation: 3523

http://jsfiddle.net/9bxwxfe2/

Use a container div set to position: relative; and then add position: absolute; to the img.

Upvotes: 2

Prakash Paramasivam
Prakash Paramasivam

Reputation: 11

CSS:

html,body{
        height: 100%;
}

img{
        position: relative;
        top: 40%;
        float:left;
}

Use float:left; in the img class. This will solve the problem and image will be displayed in expected position(40% from the top of the screen).

Upvotes: 1

Added float:left for p tag

New css,

html,body{
    height: 100%;
}

img{
    position: relative;
    top: 40%;
}
p {
    float:left
}

See jsfiddle

Upvotes: -1

Anoop B.K
Anoop B.K

Reputation: 1478

May this help you... My suggestion is to use px instead of %. It works fine.

html,body{
    height: 100%;
}

img{
    position: relative;
    top: 40px;

}

https://jsfiddle.net/vy301c07/

Upvotes: 0

Related Questions