Reputation:
Consider the following setup :
CSS :
#container {
position: relative;
width: 95%;
margin: 0 auto;
height: 100%;
}
.parent {
position: relative;
width: 100%;
height: auto;
float: left;
clear: left;
}
.child {
float: left;
width: 50%;
max-width: 200px;
}
HTML :
<body>
<div id="container">
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
<div class="parent">
<div class="child"></div>
<div class="child"></div>
</div>
</div>
<body>
If the width of the window is greater than 400px, the .child
elements will not be centered but will rather stick to the left.
I can't know the number of .child
elements in advance (but the number inside each parent will always be the same across all .parent
elements). If there's more I use JS to calculate and assign new percentages to their widths anyway so they still remain responsive (So if I have 2 child elements their widths will be 50%, if I have four their widths will be 25% etc..).
Is there a way keep the .child
elements centered with the above setup ?
Thank you for your help in advance. :-)
Upvotes: 0
Views: 74
Reputation: 1848
Add text-align: center
to the .parent
, remove the float
and change the display
property to inline-block
on the child.
.parent {
position: relative;
width: 100%;
height: auto;
float: left;
clear: left;
text-align: center;
}
.child {
display: inline-block;
width: 50%;
max-width: 200px;
}
If the space between items is an issue, split the ending tags on the child divs:
<div class="child"></div
><div class="child"></div>
le CodePen: http://codepen.io/erquhart/pen/ukHco
Upvotes: 0