Search code examples
cssreactjsflexboxbootstrap-4reactstrap

ml-auto is not pushing navbar links to the right


I'm using reactstrap and have been following this link:

https://reactstrap.github.io/components/navbar/

In the example, the <nav className='ml-auto' navbar> is pushing the <NavItem> to the right. However, what I am trying to implement (which is really similar to the example) the <NavItem> is rendering right next to the <NavbarBrand>.

I've checked the syntax like 100 times and it looks correct. The custom CSS I have, which is very little, does not seem to be overriding anything. The CSS in the console looks pretty similar and it appears to be affected by the:

.ml-auto, .mx-auto {
    margin-left: auto!important;
}

At least toggling it off in the console in the example, moves the <NavItem> right next to the <NavbarBrand> like it is in my app (which I don't want). Here is what I am looking at:

Reactstrap Example (correct spacing):

Correct spacing enter image description here

Console for my app (incorrect spacing): enter image description here enter image description here

How do I get the spacing right in my app?

It really isn't clear to me what is affecting margin-left: auto !important to work in one and not the other.


Solution

  • The navbar components (and many other components) will only work if you use them the way they've been designed to be used.

    For example, ml-auto works on sibling elements.

    It does NOT work if you destroy that sibling relationship.

    In other words, you cannot just randomly wrap elements in unnecessary divs.

    Remove the div you put around the navbar-toggler and the collapse component to make the sibling selector work as intended.

    Also: Do NOT use the !important flag as a permanent solution in any of your custom css. That flag is for quick testing only.

    P.S. You seem to have a habit of wrapping things in unnecessary divs. The container is also wrapped in such a useless div. Don't add unnecessary code for some sort of "esthetics". Only add code if it actually does something and use comments for everything else.