使用边距将div上的图标居中

时间:2012-09-27 11:36:04

标签: css

我正在尝试使用边距对图标进行居中的方法。我给图标的宽度为%,高度为%。我有

.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{

}

该方法将图标水平居中,但不是垂直居中。我想知道为什么这不起作用

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

我也有这个小提琴,但我使用的margin-top和margin-bottom是随机的http://jsfiddle.net/thiswolf/EKWWt/

4 个答案:

答案 0 :(得分:1)

由于防火墙无意义,我无法看到您的图片,但请查看此answer。这是我的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;
}

答案 1 :(得分:0)

尝试:

.container{
width:600px;
height:200px;
background-color:orange;
}
img {
margin:12% 50%;
}

答案 2 :(得分:0)

您可以尝试将图标作为背景放置。如果要求它在html中,因为它是动态加载的,那么你可以使用javascript将其替换为背景。

答案 3 :(得分:0)

我认为图像是从身体而不是从容器div中获取边距。 要水平和垂直居中图像,您可以设置位置:相对;在容器div和position:absolute;在img元素中。这可能是可能的解决方案之一。

所以css可以是这样的......

.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;
}