Home » Php » php – Making divs appear side by side while using a loop in wordpress

php – Making divs appear side by side while using a loop in wordpress

Posted by: admin February 25, 2020 Leave a comment

Questions:

I want to mak 2 divs appear in one row and then display following two in the next row and so on. I am using a php while loop to render the divs on the screen so they are appearing one below the other. How do I make it display them side by side?

Right now it looks like this:
screenshot of the way it is displaying

my code looks like this at the moment:

<?php $decadesFrontPage = new WP_Query(array(
          'posts_per_page' => 2,
          'post_type' => 'Decades',
      ));

      while($decadesFrontPage->have_posts()){
        $decadesFrontPage -> the_post(); ?>

        <div class="row">
          <div class="col-sm-6">
            <div class="card">
              <div class="card-body">
                <h5 class="card-title"><?php the_title() ?></h5>
                <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                <a href="#" class="btn btn-primary">Go somewhere</a>
              </div>
            </div>
          </div>

        </div>

      <?php } ?>
How to&Answers:

Use CSS grid it’s very easy to make that kind of layouts with it!
https://www.w3schools.com/css/css_grid.asp

.grid-container {
  display: grid;
  grid-column-gap: 50px;
  grid-template-columns: 1fr 1fr;
}
.grid-item {
  background: blue;
  color: #fff;
  font-weight:bold;
  padding:20px
}
<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item">5</div>
  <div class="grid-item">6</div>
  <div class="grid-item">7</div>
  <div class="grid-item">8</div>
  <div class="grid-item">9</div>
</div>

Answer:

1. Move the row and col outside the loop

2. Add display inline-block to card

3. Define width for the card

    <div class="row">
      <div class="col-sm-6">
<?php $decadesFrontPage = new WP_Query(array(
      'posts_per_page' => 2,
      'post_type' => 'Decades',
  ));


  while($decadesFrontPage->have_posts()){
    $decadesFrontPage -> the_post(); ?>

        <div class="card d-inline-block" style="width: 18rem;>
          <div class="card-body">
            <h5 class="card-title"><?php the_title() ?></h5>
            <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
            <a href="#" class="btn btn-primary">Go somewhere</a>
          </div>
        </div>


  <?php } ?>
      </div>

    </div>