Reputation: 22964
.container {
width: 100%;
margin: 0 auto;
display: table;
}
.child {
width: 75px;
border: 1px solid #F00;
height: 75px;
margin: 10px;
float: left;
}
.circle {
height: 25px;
width: 25px;
border: 1px solid #0F0;
border-radius: 50%;
margin: auto;
top: 25%;
position: relative;
}
I have n divs. And I have 100%
width. I want to align divs horizontally centered. Number of divs in a row is based on the size of the div.
If I set size of child
div 250px
, then for eg, if screen width is 1000px
, only 3 divs should be horizontally placed.[Because margin between divs must be considered] And left, right spacing must be equal.
I am not able to come up with a general solution. Any suggestions?
I am trying to design responsive divs
Upvotes: 3
Views: 69
Reputation: 9654
CSS:
.container{
text-align:center; /* add this */
.child{
display:inline-block; /*instead of float:left */
The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements, only their inline content.
Because we have the content display:inline-block
they are considered as inline content thus the text-align
will center its content
While the float
property "specifies that an element should be taken from the normal flow and placed along the left or right side of its container"
Upvotes: 2
Reputation: 122047
You can do this with Flexbox
.container{
width: 100%;
margin: 0 auto;
display: flex;
justify-content: center;
flex-wrap: wrap;
}
.child{
flex: 0 0 75px;
border: 1px solid #F00;
height: 75px;
margin: 10px;
position: relative;
}
.circle{
height: 25px;
width: 25px;
border: 1px solid #0F0;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: absolute;
}
<div class="container">
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
</div>
Or if you want equal space between divs you can use justify-content: space-around;
.container{
width: 100%;
margin: 0 auto;
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.child{
flex: 0 0 75px;
border: 1px solid #F00;
height: 75px;
margin: 10px;
position: relative;
}
.circle{
height: 25px;
width: 25px;
border: 1px solid #0F0;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: absolute;
}
<div class="container">
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
<div class="child"><div class="circle"></div></div>
</div>
Upvotes: 1