问题
I am having trouble getting flex to center elements (with margin) when it wraps.
It looks perfect when the screen is wide
But it is not centering it when it wraps (because of the right-margin of the first button)
Here is my code: https://jsfiddle.net/dLz7120k/2/
footer { display: flex; flex-flow: row wrap; justify-content: center; }
button { margin: 0 20px 10px 0; }
button:last-child { margin-right: 0; }
Is there any way to make it ignore the right-margin of the first button when it wraps?
(I don't want to change the spacing between the buttons, or add unnecessary margins before/after the first/last button)
回答1:
Split the margins between the button
elements - make it margin: 5px 10px
for both so that you can retain 20px between the buttons horizontally and 5px between them vertically when they wrap.
To avoid the wrapping a bit too early, you can use negative margins on the footer
container element to adjust for the margins causing this early wrapping (thanks to LGSon for pointing out this trick). See modified demo below:
* {
font-size: 18px;
}
#modal {
margin: 10%;
padding: 15px;
width: 50%;
border: 1px solid blue;
}
p {
text-align: center;
}
footer {
display: flex;
flex-flow: row wrap;
justify-content: center;
margin: 0 -20px; /* extend by this amount on both sides */
}
button {
margin: 5px 10px;
}
<div id='modal'>
<p>Some text and some paragraph</p>
<footer>
<button>Cancel</button>
<button>Continue</button>
</footer>
</div>
回答2:
You have to write @media
style for the width of the screen when it wraps and remove margin-right in there.
E.g.
@media screen and (max-width: 768px) {
button {
margin: 0 0 10px;
}
}
来源:https://stackoverflow.com/questions/55176434/flex-to-ignore-side-margin-when-centering-elements