I think the only way to accomplish this with flexbox is to wrap the text in a new element, as @Kukkuz made another answer .
Without this extra shell, you can still get equal spaced separators, but the red background is not limited by the length of the text.
The following is an example:
- No changes to HTML.
- No need for pseudo-elements.
- There is no need for absolute positioning.
If the background color for the text is not needed, delete it, and that should be all you need.
.Flex { display: flex; list-style: none; margin: 0; padding: 0; } .Flex-item { flex: 1 1 auto; background: red; } .Flex-item { text-align: center; } .Flex-item:first-child { text-align: left; } .Flex-item:last-child { text-align: right; } .Flex-item + .Flex-item { border-left: 1px solid white; } .Container { max-width: 70%; margin-right: auto; margin-left: auto; background: blue; padding-top: 20px; padding-bottom: 20px; }
<div class="Container"> <ul class="Flex"> <li class="Flex-item">Lorem</li> <li class="Flex-item">consectetur</li> <li class="Flex-item">vestibulum</li> <li class="Flex-item">nec</li> <li class="Flex-item">condimentum</li> </ul> </div>
If you can add a span around the text, which allows you to limit the red background to the length of the text, then you will all set:
.Flex { display: flex; list-style: none; margin: 0; padding: 0; } .Flex-item { flex: 1 1 auto; display: inline-flex; justify-content: center; } .Flex-item span { background-color: red; } .Flex-item:first-child span { margin-right: auto; } .Flex-item:last-child span { margin-left: auto; } .Flex-item + .Flex-item { border-left: 1px solid white; } .Container { max-width: 70%; margin-right: auto; margin-left: auto; background: blue; padding-top: 20px; padding-bottom: 20px; }
<div class="Container"> <ul class="Flex"> <li class="Flex-item"><span>Lorem</span></li> <li class="Flex-item"><span>consectetur</span></li> <li class="Flex-item"><span>vestibulum</span></li> <li class="Flex-item"><span>nec</span></li> <li class="Flex-item"><span>condimentum</span></li> </ul> </div>
Michael_B
source share