问题
In the page here: https://irfan.io
I have tried centring the smaller circles every-way I can think of and they either don't get centred or the centring is not responsive-- meaning it fails when the viewport is changed.
They are all of class .small and they are children of #main.
I have tried flexbox:
#main{
display:flex;
align-items:center;
justify-content:center;
}
.small{
display:flex;
}
I have tried giving wrapping the .small elements in a container and giving that a fixed width and centring with -0.5 of the width:
#smallContainer{
width:500px;
margin-left:-250px;
position:relative;
left:50%;
}
I also figured since they were inline-block elements I could use text-align:center;
on the .small element, but that didn't work.
#small{
text-align:center;
}
I can't seem to figure out how to centre 3 small circles so that the middle one is in the vertical-middle like the bigger circle ( .big ), which I centred using the 2nd technique.
Does anyone have any ideas on how to do this?
回答1:
you can try this:
HTML:
<div id="main">
<div id="smallContainer">
<div class="small">
text
</div>
<div class="small">
text
</div>
<div class="small">
text
</div>
</div>
</div>
CSS:
#main{
display:flex;
align-items:center;
justify-content:center;
position:relative;
}
.small{
display:flex;.
text-align:center;
display:inline-block;
width:100px;
height:100px;
border:1px solid black;
}
#smallContainer{
margin-left:0 auto;
position:relative;
}
fiddle here
What i did is simple.. just make #main and #smallContainer position relative, remove the left and width from #smallContainer to make it expand only according to its children, then put margin:0 auto; to #smallContainer. This way even if the viewport change you're sure the .small div's are centered.
EDIT
I updated the fiddle, I just removed the display:inline-block; from .small in css.
Dont forget to mark this as answer if it gives you what you need my friend :)
回答2:
You have a mistake. Your inline-block elements has a left of 50% (even you will center, there are a 50% more to the right).
You can solve like this:
#smallContainer { text-align: center; }
.small { left: 0; }
来源:https://stackoverflow.com/questions/31781536/centering-inline-block-elements-when-flexbox-and-classic-techniques-dont-work