Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Previous and Next button with flexbox, how to place them at the left and the right respectively?

I am trying to build a simple pagination system where the user can click on a Next/Prev button to navigate to the next/previous page. I want to place the buttons to the left of the screen and to the right respectively and I did that with flexbox by using justify-content: space-between.

It works fine when the two buttons are displayed but I am using some PHP logic to conditionally display them based on the ability to navigate to the previous or the next page. For instance, on the 1st page, one can’t navigate to a previous page so I don’t the Prev button to be present. And that’s where the problem appears : if the Prev button is absent, the Next button is placed on the left.

What can I do to keep the Next button to the right even if the Prev button is absent?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

div{
  width: 100%;
  display: flex;
  justify-content: space-between;
}

a.a{
  background: #88f;
  color: #fff;
  padding: 5px 20px;
}

/*a.a:nth-child(1){
  display: none;
}*/
<div>
<a class="a">Prev</a>
<a class="a">Next</a>
</div>

The PHP logic is very simple, it looks like this :

<?php if($no_pages_left):?>
<a class="a">Prev</a>
<?php endif ?>
<?php if($no_pages_right):?>
<a class="a">Next</a>
<?php endif ?>

>Solution :

:nth-child(2 of .a) {
  margin-left: auto;
}

will fix it, automatically expanding the element’s left margin as much as possible.

div {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-top: 50px; /* for demo */
}

a.a {
  background: #88f;
  color: #fff;
  padding: 5px 20px;
}

 :nth-child(2 of .a) {
  margin-left: auto;
}

a.a:nth-child(1) {
  display: none;
}
<div>
  <a class="a">Prev</a>
  <a class="a">Next</a>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading