Edward Tanguay
Edward Tanguay

Reputation: 193312

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.

In the following example, I want the gray boxes ("assetInfoBody") to be centered within the green boxes ("assetBox"). What else can I try here beside text-align:center and 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>

Upvotes: 0

Views: 148

Answers (2)

aivou
aivou

Reputation: 126

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. By also applying text-align:center to .centeredItem you're able to always keep the image centered within it.

Upvotes: 1

N4553R
N4553R

Reputation: 188

probably you want a css like that:

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

Upvotes: 0

Related Questions