Flex to ignore side margin when centering elements

…衆ロ難τιáo~ 提交于 2020-01-05 04:09:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!