简体   繁体   中英

Append flex item without affecting centered siblings

I'm trying to add an action button to the end of a grid of items. The catch is that the button element can't influence the centering of the items, but must break as if it was part of the grid - just offset.

I've created a demo illustrating the closes approach.

.flex-container {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}

.button {
  margin-right: -120px;
  width: 120px;
}

Here using a negative margin on the trailing button the items are correctly centered however the button overflows the container and doesn't break onto a new line correctly.

Does anyone know a smart approach to this layout? It is even possible with pure css?

 * { box-sizing: border-box; }.flex-container { padding: 0; margin: auto; list-style: none; display: flex; flex-flow: row wrap; justify-content: center; max-width: 800px; }.flex-item { border: 1px solid yellow; background: tomato; padding: 5px; width: 200px; height: 150px; margin-top: 10px; line-height: 150px; color: white; font-weight: bold; font-size: 3em; text-align: center; }.button { margin-right: -120px; width: 120px; height: 150px; font-size: 2em; background: teal; }
 <ul class="flex-container"> <li class="flex-item">1</li> <li class="flex-item">2</li> <li class="flex-item">3</li> <li class="flex-item">4</li> <li class="flex-item">5</li> <li class="flex-item">6</li> <span class="flex-item button">Button</span> </ul>

I don't believe it's possible with pure CSS.

  1. The centering occurs through the distribution of free space in the container. The button element, appended to the last item, will occupy space. Therefore, it will affect the centering of its siblings.

  2. If you choose to use absolute positioning to remove the button from the document flow, it will no longer occupy space in the container, and will not affect the centering of other flex items. However, it will also stop wrapping because it will lose its association with its siblings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM