Search code examples
cssreactjspositionalignmentreact-bootstrap

How to position this button to the right in this Navbar


I'm new to this and learning React.
I try to set the hamburger toggle button in this CodeSandBox to always be to the right but I have problems. The toogle must always be to the right with like margin-right: 50px

I use the react-bootstrap NavBar. As the image show the toggle button must be on the right but it's stuck.

enter image description here

When I set margin-left: 100px; the buttons in the above image is pushed on top of toggle

 .form-inline {
    width: 100%;
    margin-left: 100px;
  }

I also want margin-left but if I remove that it look ok:

enter image description here

I also use the <Form inline> so I have the items in a line and there are 2 columns only. I try to make one column only and it did not work..

I have tried an abundant of combinations to make the toggle button stick to right side but no luck please advice.


Solution

  • Well, there are some approaches to solve your current problem or even make your code structure much better. As @pat said earlier it's better to control your item positioning with grid tools, like flexbox and its relevant properties.

    But if you just intend to move your toggle to the right side and you just defined two Col element (Columns), you can simply move it around its container with text-align property (In your particular case: text-align: right;). So if you want to do it with react-bootstrap built-in classes you can use text-right on the toggle container like this:

    <Navbar expand="false" bg="dark" variant="dark" fixed="top" collapseOnSelect className={`navbar`}>
      /* navbar brand */
      <Col>
          /* first col items */
      </Col>
      <Col className="text-right">
          <Navbar.Toggle aria-controls="responsive-navbar-nav" />
      </Col>
    </Navbar>
    

    Also, there is no need to add margin-left property to the form-inline class, because it will only move the left column to the right.

    Update

    As I said earlier for managing your blocks it's better to use grid tools. So I just create a sandbox for that that you can see here:

    CodeSandbox

    I the above sandbox I just removed the Col items and add d-flex (This is the equivalent of display: flex;, you can read more about flexbox here) to the parent, which is the navbar itself. Then just add the justify-content-between which make sure there is always space between items in the same row whenever there is extra space available and finally to align them vertically I just used align-items-center. To make sure the form elements are always in the same line just added the flex-nowrap to the form element itself. Well, the elements in the smaller viewport will stack on top of each other, which the normal behaviour of flexbox but you can modify it however you want.