2

I have a grid layout of 2 columns. i have 5 div , my 5th div coming on left and i want my 5th div to be centered.

How can i achieve that using any grid property?

My Output:

My output

This is what I want:

enter image description here

Here is my code:

<style>
        .container{
            display: grid;
            grid-template-columns: 200px 200px;
            gap: 10px;
        }

        .box{
            padding: 20px;
            background-color: burlywood;
            border: 1px solid red;
        }
</style>

<div class="container">
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
</div>
Dhairya Lakhera
  • 4,445
  • 3
  • 35
  • 62
  • 2
    Does this answer your question? [How to center elements on the last row in CSS Grid?](https://stackoverflow.com/questions/46276793/how-to-center-elements-on-the-last-row-in-css-grid) – vmank Oct 03 '20 at 17:48

2 Answers2

3

You can select the last .box in your DOM to span across both columns.

.container {
  display: grid;
  grid-template-columns: 200px 200px;
  gap: 10px;
}

.box {
  padding: 20px;
  background-color: burlywood;
  border: 1px solid red;
}

.container .box:last-child {
 justify-self: center;
 width: calc(200px - 20px);
 grid-column-start: span 2;
}
<div class="container">
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
</div>

The main piece of code to look at here is this:

.container .box:last-child {
 justify-self: center;
 width: calc(200px - 20px);
 grid-column-start: span 2;
}

grid-column-start tells the browser to render where the very left side of the .box start from based on your grid. Using span 2 says that the .box will start from its natural position and span 2 columns.

koralarts
  • 2,062
  • 4
  • 30
  • 48
-1

There are different ways to do it, but check out my code below with flexboxes. justify-content: space-around made it center

        .container{
            max-width: 500px;
            background: red;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            align-items: middle;
            justify-content: space-around
        }

        .box{
            padding: 20px;
            background-color: burlywood;
            border: 1px solid red;
            width: 200px

        }
<div class="container">
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
    <div class="box">Lorem Lipsum</div>
</div>
Jaocampooo
  • 482
  • 3
  • 10