Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move image in div with CSS?

Tags:

html

css

I have an image located inside a div, I am trying to move it 50 px down and 50 px left in order to have everything complete. But I am not sure how to edit the image in the CSS since I don't know what code to put in to connect the photo to the css.

My code:

#OverviewText4 img:MoneyIcon.png {
  width: 150px;
  height: 150px;
  position: absolute;
  top: 50px;
  left: 50px;
}
<div id="OverviewText4">
  <img src="MoneyIcon.png" />
</div>

Thanks for helping

like image 399
Sid Avatar asked Dec 05 '16 11:12

Sid


3 Answers

Remove the image name from your declaration and make sure your container is set to position: relative so that your image is absolutely positioned against the right containing element in this instance #OverviewText4

#OverviewText4 {
    position: relative;
}

#OverviewText4 img {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 50px;
    left: 50px;
}
like image 193
elmarko Avatar answered Nov 14 '22 19:11

elmarko


You have to add position:relative to parent <div> and then add position: absolute; to the <img>. Like this:

#OverviewText4{
  position: relative;
}

#OverviewText4 img{
  width: 150px;
  height: 150px;
  position: absolute;
  top: 50px;
  left: 50px;
}
<div id="OverviewText4"> 
  <img src="MoneyIcon.png" />
</div>

     
like image 34
Sebastian Kaczmarek Avatar answered Nov 14 '22 17:11

Sebastian Kaczmarek


There are many ways to do this in CSS as per the multitude of answers. If I might suggest, since the image name in your example is related to iconography a slightly different approach:

#OverviewText4 {
    position: relative;
}
#OverviewText4:before {
  content: "";
  background: transparent url(MoneyIcon.png) scroll no-repeat 0 0;
  background-size: cover;
  width: 150px;
  height: 150px;
  position: absolute;
  display: block;
  top: 50px;
  left: 50px;
}

https://jsfiddle.net/zk8su1qw/

This way you don't even need an img tag in the HTML, which is desirable if its just presentational.

There is also an assumption in this answer that you want the image displayed over the top of any content in the OverviewText4 div, rather than having content flow around the image. If this is not the case you would want to use margins and keep the image position: static or relative.

like image 3
AndFisher Avatar answered Nov 14 '22 18:11

AndFisher