2012-08-07 110 views
0

我想要在每个DIV内有一个在大DIV内左移的图像。如何在div中居中对齐一个div的图像?

在下面的示例中,我希望灰色框(“assetInfoBody”)在绿色框(“assetBox”)内居中。还有什么我可以在这里旁边的文字对齐:center和margin:auto?

enter image description here

<!DOCTYPE html> 
<html> 
    <head> 
     <style type="text/css"> 
      #assets { 
       background-color: orange; 
       padding: 5px; 
       width: 100%; 
       height: 100%; 
      } 
      .assetbox { 
       background-color: lightgreen; 
       float: left; 
       width: 100px; 
       margin-right: 5px; 
          text-align: center; 
      } 

      .assetInfoBody { 
       background-color: grey; 
       position: relative; 
       width: 80px; 
       text-align: center; 
      } 

      .centeredItem { 
       margin-left: auto; 
       margin-right: auto; 
       top: 0px; 
      } 

     </style> 
    </head> 
    <body> 
     <div id="assets"> 
      <div class="assetbox"> 
       <div class="assetInfoBody"> 
        <div class="centeredItem"> 
         <img src="images/box.png"/> 
        </div> 
       </div> 
      </div> 
      <div class="assetbox"> 
       <div class="assetInfoBody"> 
        <div class="centeredItem"> 
         <img src="images/box.png"/> 
        </div> 
       </div> 
      </div> 
      <div class="assetbox"> 
       <div class="assetInfoBody"> 
        <div class="centeredItem"> 
         <img src="images/box.png"/> 
        </div> 
       </div> 
      </div> 
     </div> 
    </body> 
</html> 
+1

没有作为一个CSS专家,我看你有没有保证金左:自动; margin-right:auto;在居中的项目中。 如果您将其复制/粘贴到assetInfoBody中,这不起作用?只是问问。 – 2012-08-07 13:36:31

+0

实际上你在上面的例子中是正确的,问题是我们现在需要assetInfoBody是绝对的,以匹配这个例子需要内置的HTML,因为图形的圆角被应用到它,所以它有成为一个稍微不同的问题,但谢谢你的澄清 – 2012-08-07 13:49:47

回答

1

的你如何能做到这一点的参考见this example。由于您的班级.assetInfoBody班级设置了宽度,因此您可以通过将规则margin:0 auto应用于该班级来对齐.centeredItem。通过将text-align:center应用于.centeredItem,您可以始终保持图像居中。

0

可能是你想要的CSS这样的:

#assets { 
    background-color: orange; 
    padding: 5px; 
    width: 100%; 
} 
.assetbox { 
    background-color: lightgreen; 
    display: inline-block; 
    width: 100px; 
    margin-right: 5px; 
} 

.assetInfoBody { 
    background-color: grey; 
    margin: 0 auto !important; 
    width: 80px; 
} 

.centeredItem { 
    margin-left: auto; 
    margin-right: auto; 
}