Besart Marku
Besart Marku

Reputation: 543

How to position element to the right?

I have 2 buttons in the end of the form. I am using styled components and react. Problem is that when the left aligned button is being hidden, the other button which is supposed to stay in the right, comes to the left. Below is my css(and screenshot of layout), what do i need to add/change?

const ButtonsContainer = styled.div`
  display: flex;
  justify-content: space-between;
`;

meanwhile the code on the jsx part

      <div>
        <ButtonsContainer>
          {tabIndex != 0 && (
              <Button
                label=" Go Back"               
              />
          )}
          {nextStep > 0 && (
              <Button                  
                label=" Next Step"
              />
          )}
        </ButtonsContainer>
      </div>

enter image description here

Upvotes: 1

Views: 8458

Answers (3)

Hassan ALAMI
Hassan ALAMI

Reputation: 347

You can simply align the right button to right using text-align, the left button will stay always left because it's the default alignement for inline elements. In the suggestion below i'm using a div as a row, and two divs inside with 50% max-width.

.row {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}

.col-50 {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 50%;
  flex: 0 0 50%;
  max-width: 50%;
}

.text-right {
  text-align: right;
}
<div class="row">
  <div class="col-50">
    <button>
      Go Back
    </button>
  </div>
  <div class="col-50 text-right">
    <button>
      Next Step
    </button>
  </div>
</div>

Upvotes: 1

Loup
Loup

Reputation: 9

Are you using display: none to hide the element? If so you should probably switch to using visibility: hidden.

display: none removes the element from the page totally, whereas visibility: hidden will hide the element but also preserve the space it was taking up.

Upvotes: 0

user2343647
user2343647

Reputation: 661

You could have 2 flex container, one for the left button, the other for the right button:

(css only)

.buttons-container {
   display: flex;
}

.button-left {
   flex: 0 0 50%;
   display: flex;
   justify-content: flex-start;
}

.button-right {
   flex: 0 0 50%;
   display: flex;
   justify-content: flex-end;
}
<div class="buttons-container">
   <div class="button-left"><button></button></div>
   <div class="button-right"><button></button></div>
</div>

Sorry, I don't know styled-components, but you get the idea I am sure.

There are other tricks, you should put some time to study flexbox.

Upvotes: 2

Related Questions