1

I am looking for a way to right-justify specific columns (not all columns) in a grid in CSS without having to explicitly specify a special class or style for each column entry. For example:

<style>
    .myclass {
        display: grid;
        grid-template-columns: 100px 100px 100px 100px;
    }
</style>

<div class="myclass">
    <span>AAAA</span>
    <span>BBBB</span>
    <span>CCCC</span>
    <span>DDDD</span>

    <span>EEEE</span>
    <span>FFFF</span>
    <span>GGGG</span>
    <span>HHHH</span>
</div>

So, I want the first and third columns right justified, and the second and fourth columns left justified without having to explicitly specify style or class for each span.

Thanks!

4
  • 2
    did you consider nth-child selector? Commented May 19, 2020 at 11:54
  • Assuming the columns follow the DOM order of course....☺ Commented May 19, 2020 at 11:55
  • The problem with nth-child selector is that I want it auto-repeated to affect all elements in that column not specified one (nth-children). Commented May 19, 2020 at 11:57
  • nth-child can auto repeat to target a group of specific elements Commented May 19, 2020 at 11:58

1 Answer 1

3

nth-child selector can do the trick

.myclass {
  display: grid;
  grid-template-columns: 100px 100px 100px 100px;
  grid-gap: 10px;
}

span:nth-child(2n+1) {
  background: #eee;
  display: flex;
  justify-content: flex-end;
}
<div class="myclass">
  <span>AAAA</span>
  <span>BBBB</span>
  <span>CCCC</span>
  <span>DDDD</span>

  <span>EEEE</span>
  <span>FFFF</span>
  <span>GGGG</span>
  <span>HHHH</span>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.