Grid::Right align grid item
Asked Answered
F

4

13

By using the grid positioning of the buttons to the right. Can anyone point me in the right direction?

.container {
  width: 500px;
  border: 1px solid red;
}

.grid {
  display: grid;
  grid-gap: 5px;
  grid-auto-flow: column;
  width: 100px;
}
<div class="container">
  <div class="grid">
    <button>test 1</button>
    <button>test 2</button>
  </div>
</div>

In the above scenario, how do I move the two buttons to the end of the parent div?

Fokos answered 29/11, 2018 at 5:0 Comment(0)
W
11

The problem is.. you had set the grid width to 100px

Instead set column width:100px inside the grid, because grid is the container also use justify-content:end; to align the content to the right side.

.container {
  width: 500px;
  border: 1px solid red;
}

.grid {
  display: grid;
  grid-gap: 5px;
  grid-auto-flow: column;
  width: 100%;
  grid-template-columns: 100px 100px;
  justify-content: end;
}
 button{display:inline-block;}
 
<div class="container">
  <div class="grid">
    <button>test 1</button>
    <button>test 2</button>
  </div>
</div>

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Box_Alignment_in_CSS_Grid_Layout

Wanwand answered 29/11, 2018 at 5:26 Comment(1)
It seems that : with grid-template-columns: repeat(10, 1fr); "justify-content:end" doesn't work. I just want to get an auto-width and align right, avoid hard-coding width of items. what's the workaround?Stickup
F
4

Hope this is helpful for you!

.container {
  width: 500px;
  border: 1px solid red;
}

.grid {
  display: grid;
  grid-gap: 5px;
  grid-auto-flow: column;
  width: 100px;
  margin: 0 0 0 auto; //added
}
<div class="container">
  <div class="grid">
    <button>test 1</button>
    <button>test 2</button>
  </div>
</div>
Fifth answered 29/11, 2018 at 5:20 Comment(0)
I
2

use justify-content: end; & grid-template-columns: 100px 100px;

.container {
  width: 500px;
  border: 1px solid red;
}

.grid {
  display: grid;
  grid-gap: 5px;
  grid-auto-flow: column;
  width: 100%;
  grid-template-columns: 100px 100px;
  justify-content: end;
}
<div class="container">
  <div class="grid">
    <button>test 1</button>
    <button>test 2</button>
  </div>
</div>
Infecund answered 29/11, 2018 at 5:12 Comment(0)
C
1

You can simply use margin:auto for this:

.container {
  width: 500px;
  border: 1px solid red;
}

.grid {
  display: grid;
  grid-gap: 5px;
  grid-auto-flow: column;
  margin-left:auto;
  width:100px;
}
<div class="container">
  <div class="grid">
    <button>test 1</button>
    <button>test 2</button>
  </div>
</div>
Contrapuntist answered 15/7, 2022 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.