Reputation: 1996
I've got two rows of boxes inside a container and I need them to be in the center of the page. I cannot set the width of the container because the stuff inside might change.
The reason why I don't break up the boxes into two rows within the HTML is because I'm using media queries to force two rows when the screen is tight, but it would naturally be one row when there is space on the screen.
Note that I have an empty div for clearfix. Feel free to remove it if you think there is a better method.
Here's my HTML:
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
And here's my CSS:
.box {
width: 50px;
height: 50px;
background: red;
color: white;
margin: 10px;
float: left;
}
.box:nth-child(3) {
clear: both;
}
.container {
background-color: grey;
}
The container is grey for illustration only, in my app it would be clear.
Fiddle here
Upvotes: 1
Views: 352
Reputation: 11
`<div class="container">
<div align="center" style="padding-left: 532px;">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
</div>`
Upvotes: 0
Reputation: 1074
You can just add a container div and give it a width and margin: 0 auto; http://jsfiddle.net/oc0w0n4n/1/
.center{
margin: 0 auto;
width:140px;
}
<div class="center">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
Upvotes: 1
Reputation: 241208
If you can wrap the elements, then you could set the display
of the wrapper element to inline-block
and then add text-align: center
to the parent element for horizontal centering:
.container {
background-color: grey;
text-align: center;
}
.container .center-wrapper {
display: inline-block;
}
.box {
text-align: left;
}
.box {
width: 50px;
height: 50px;
background: red;
color: white;
margin: 10px;
float: left;
text-align: left;
}
.box:nth-child(3) {
clear: both;
}
.container {
background-color: grey;
text-align: center;
}
.container .center-wrapper {
display: inline-block;
}
<div class="container">
<div class="center-wrapper">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
</div>
Using flexboxes, you could also use the following:
.container {
background-color: grey;
display: flex;
justify-content: center;
}
.box {
width: 50px;
height: 50px;
background: red;
color: white;
margin: 10px;
float: left;
}
.box:nth-child(3) {
clear: both;
}
.container {
background-color: grey;
display: flex;
justify-content: center;
}
<div class="container">
<div class="center-wrapper">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div style="clear: both;"></div>
</div>
</div>
Upvotes: 1