0

I am trying a method of centering an icon using margins.I am giving the icon a width in % and the height in % too.I have

.container{
width:600px;
height:200px;
background-color:orange;
}
img {
width:6%;
margin-left:47%;
margin-right:47%;
height:16%;
margin-top:12%;
margin-bottom:12%;
}
body{

}

The method centers the icon horizontally but not vertically.I wonder why this wont work

img {
    width:6%;
    margin-left:47%;
    margin-right:47%;
    height:16%;
    margin-top:42%;
    margin-bottom:42%;
    }

I also have this fiddle but the margin-top and margin-bottom i have used are random http://jsfiddle.net/thiswolf/EKWWt/

Gandalf
  • 1
  • 29
  • 94
  • 165
  • For fixed layout: http://jsfiddle.net/EKWWt/2/ – Riz Sep 27 '12 at 11:44
  • Using a percentage for `margin-[top|bottom]` will give a margin that is a percentage of the *width* of the element. `margin-[top|bottom]: n%` is not what you want here. – thirtydot Sep 27 '12 at 11:44

4 Answers4

1

I can't see your image because of firewall nonsense, but take a look at this answer. Also here is my forked fiddle.

.container{
    width:600px;
    height:200px;
    background-color:orange;
    text-align:center;
    line-height:138px; /*You'll have to play around with this value*/
}

img {
    vertical-align:middle;
}
Community
  • 1
  • 1
John
  • 13,197
  • 7
  • 51
  • 101
  • I have that in a fiddle http://jsfiddle.net/thiswolf/HDN4M/ but i am testing it on bootstrap.UPDATE:Works on twitter bootstrap too. – Gandalf Sep 27 '12 at 12:05
  • @Dev I am guessing that the height of the line height and the height of the div have to be the same? – John Sep 27 '12 at 12:07
0

Try with:

.container{
width:600px;
height:200px;
background-color:orange;
}
img {
margin:12% 50%;
}
Prasath Albert
  • 1,447
  • 10
  • 20
0

You could try just placing the icon in as a background instead. If it's a requirement that it be in the html because it's loaded dynamically, then you can use javascript to replace it as a background.

FluffyJack
  • 1,732
  • 10
  • 15
0

I think the image is taking margins from the body and not from the container div. To centre image horizontally and vertically you can set position: relative; in the container div and position: absolute; in img element. This can be one of the possible solution.

So the css can be like this...

.container{
  width:600px;
  height:200px;
  background-color:orange;
    position: relative;
 }
 img {
 width:6%;
 margin-left:47%;
 margin-right:47%;
 height:16%;
 margin-top:42%;
 margin-bottom:42%;
    position: absolute;
}
RVC
  • 69
  • 4