Search code examples
htmlcsscss-grid

Is it possible to put buttons under each element in a grid?


I'm trying to make a grid with items/pizza toppings to order, and I would like an "Add to cart" button under each item in the grid. How would I go about doing that?

So far I've tried simply putting a button with a line break under an element but as assumed, that didn't work.

Here is the relevant code I have in the body:

.wrapper {
  width: 90%;
  margin: 0 auto;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-auto-rows: 200px;
  grid-row-gap: 30px;
  grid-column-gap: 10px;
}

.item {
  background: firebrick;
  color: white;
  padding: 10px;
}

.item:nth-child(even) {
  background: rgb(139, 19, 19);
}

.add {
  margin-bottom: 100px;
}

button {
  margin-bottom: 100px;
}

#container {
  background-color: maroon;
  width: 1500px;
  height: 1200px;
  margin-left: auto;
  margin-right: auto;
  border-color: black;
  border-width: 10px;
  border-style: double;
}
<div id="container">
  <div id="header">
    <h1> Pizza Planet </h1>
    <script src="index.js"></script>
  </div>
  <div id="content">
    <h2>Select your items:</h2>
    <div class="wrapper">
      <div class="item">1</div>
      <div class="add"><button>Add To Cart</button></div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item">5</div>
      <div class="item">6</div>
      <div class="item">7</div>
      <div class="item">8</div>
      <div class="item">9</div>
    </div>
  </div>
</div>

All that does is make a huge gap for another cell on the grid with a tiny add to cart button on there. Any help would be appreciated, thank you.


Solution

  • One approach might be to use CSS grid to achieve what you require. A simple grid layout for what you describe above could be done like this:

    .item img {
      width:100%;
      /* Causes the button to sit below the img */
      display:block;
    }
    
    .item button {
      width:100%;
    }
    
    .grid {
      /* Specifies css grid to be used */
      display:grid; 
      /* Specifies the number of columns and sizes in the grid */
      grid-template-columns: 1fr 1fr;
      /* Specifies spacing between grid cells */
      grid-gap:1rem;
    }
    <div class="grid">
      <div class="item">
        <img src="http://wallpapersdsc.net/wp-content/uploads/2015/11/Pizza_Images12.jpg" />
        <button>Order</button>
      </div>
      <div class="item">
        <img src="http://wallpapersdsc.net/wp-content/uploads/2015/11/Pizza_Images12.jpg" />
        <button>Order</button>
      </div>
      <div class="item">
        <img src="http://wallpapersdsc.net/wp-content/uploads/2015/11/Pizza_Images12.jpg" />
        <button>Order</button>
      </div>
      <div class="item">
        <img src="http://wallpapersdsc.net/wp-content/uploads/2015/11/Pizza_Images12.jpg" />
        <button>Order</button>
      </div>
    </div>