[英]How can I center a div with a centered image inside a div?
I want to have an image centered within each DIV that is floating left within a larger DIV. 我想在每个DIV中居中放置一个图像,该图像在较大的DIV中向左浮动。
In the following example, I want the gray boxes ("assetInfoBody") to be centered within the green boxes ("assetBox"). 在下面的示例中,我希望灰色框(“ assetInfoBody”)在绿色框(“ assetBox”)中居中。 What else can I try here beside text-align:center and margin:auto?
除了text-align:center和margin:auto之外,我还能在这里尝试什么?
<!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>
See this example for a reference to how you could achieve this. 请参阅此示例 ,以获取有关如何实现此目标的参考。 As your class
.assetInfoBody
class has a set width you can align the .centeredItem
by applying the rule margin:0 auto
to it. 由于您的
.assetInfoBody
类具有设置的宽度,因此可以通过将规则margin:0 auto
应用于.centeredItem
来对齐它。 By also applying text-align:center
to .centeredItem
you're able to always keep the image centered within it. 通过还将
text-align:center
应用于.centeredItem
您可以始终使图像居中。
probably you want a css like that: 可能您想要这样的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.