Alexander Solonik Alexander Solonik - 5 months ago 12
CSS Question

justify-content: space-between failing to align elements as expected

I needed to use flexbox to center my navigation and hence i came up with the following:

FIDDLE HERE

HTML:

<nav role="navigation" class="navbar navbar-default navbar-fixed-top">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="index.html" class="navbar-brand">
<img src="https://upload.wikimedia.org/wikipedia/commons/4/48/EBay_logo.png" alt="Logo">
</a>
</div>
<!-- Collection of nav links and other content for toggling -->
<div id="navbarCollapse" class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="index.html">Home</a></li>
<li><a href="consulting.html">CONSULTING</a></li>
<li><a href="devices.html">Medical Devices</a></li>
<li><a href="">Servises</a></li>
<li><a href="">News</a></li>
<li><a href="">Contact Us</a></li>
</ul>
</div>
</div>
</nav>


As you can see from the HTML , the
.container
has two child elements, I have the following CSS applied to the
.container
element:

.navbar-default > .container{
display: flex;
align-items:center;
justify-content:space-between;
}


The problem is
space-between
doesn't make the two child elements of the container to be of the left and right edges of the container, the behaviour that i want is that the two child elements should be on the left and right edge, this can be achieved using floats, I.E i float one child to the left and one to the right , also if you apply
flex-start
and
flex-end
the elements will be pulled to the edge but , with
flex-start
and
flex-end
, both elements will be pulled to one side , Hence i need to use
space-between
.

Can somebody tell me why is
space-between
not working ? This bug is causing a huge alignment issue on my whole site, please somebody tell me what am i doing wrong.

Answer

The problem is a conflict with the Bootstrap stylesheet, which places pseudo-elements in your flex container. This causes space-between to see multiple flex items as opposed to just two.

Here's your flex container:

enter image description here


Here's Bootstrap's ::before and ::after pseudo-elements (or pseudo-flex items):

enter image description here


Let's put some content in the pseudos:

enter image description here


Remove (or override) the pseudo-elements and your problem is gone:

enter image description here


More details about flex containers and pseudo-elements: