Reputation: 165
I have a number of boxes with content in them. The number of boxes per row change based on how wide the browser window is.
How can I make it so that the entire collection of boxes is always centered horizontally on the page?
Here is a reference: FIDDLE
HTML:
<body>
<div class="centered">
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
</div>
</body>
CSS:
body {
background-color:grey;
margin:0px;
padding:0px;
}
.centered {
min-width:620px;
max-width:1920px;
margin-right:auto;
margin-left:auto;
}
.segment {
float:left;
height:300px;
width:300px;
margin:5px;
background-color:red;
}
I am open to JavaScript and jQuery solutions but if possible I would prefer to stick to HTML and CSS.
Upvotes: 3
Views: 88
Reputation: 691
it is hard for only HTML/CSS to resolve your issue perfectly. A very simple JS solution is proposed here.
<body>
<div class="centered">
<span id="segmentList">
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
<div class="segment">Content</div>
</span>
</div>
</body>
<script type="text/javascript">
$('div.centered').width($('#segmentList').width());
<script>
Upvotes: 1
Reputation: 16140
By setting a different width to the container depending on the width:
@media screen { .centered { width: 620px } }
@media screen and (min-width: 930px) { .centered { width: 930px } }
@media screen and (min-width: 1240px) { .centered { width: 1240px } }
@media screen and (min-width: 1550px) { .centered { width: 1550px } }
@media screen and (min-width: 1860px) { .centered { width: 1860px } }
The numbers are multiples of 310 (300 + 5 pixels margin each side)
This way also the orphaned tiles in the end don't get centered.
Upvotes: -1
Reputation: 20418
Try this
.centered {
min-width:640px;
max-width:1920px;
margin-right:auto;
margin-left:auto;
display:inline-block;
text-align:center;
}
.segment {
display:inline-block;
height:300px;
width:300px;
margin:5px;
background-color:red;
}
Upvotes: 1
Reputation: 1289
i do this
1 -
.centered { display:block; text-align:center; }
2 -
.segment
remove float
add display:inline-block
have fun
Upvotes: 1