Home > other >  How to ignore tag when set grid-template-columns property?
How to ignore tag when set grid-template-columns property?

Time:04-08

How to display only the div in three columns using css grid for this html structure?

codepen

section {
  display:grid;
  grid-template-columns: repeat(3, 150px);
  grid-gap: 20px;
}
div { background:blue;height:30px;}

<section>
  <div>1</div>
  <span></span>
  <div>2</div>
  <span></span>
  <div>3</div>
  <span></span>
  <div>4</div>
  <span></span>
  <div>5</div>
  <span></span>
  <div>6</div>
  <span></span>
</section>

I use grid-template-columns to display three div in row. but I also want to ignore the span. is there some css property that can ignore the span when set the columns?

the expected results should be:

 div1 div2 div3
 div4 div5 div6

CodePudding user response:

It's due to the span between div element that are considered as other column

section {
  display: grid;
  grid-template-columns: repeat(3, 150px);
  grid-gap: 20px;
}

div {
  background: blue;
  height: 30px;
}

span {
  background: red;
}
<section>
  <div>1</div>
  <span></span>
  <div>2</div>
  <span></span>
  <div>3</div>
  <span></span>
  <div>4</div>
  <span></span>
  <div>5</div>
  <span></span>
  <div>6</div>
  <span></span>
</section>

an idea can be to set section with position:relative and span position:absolute to place span inside relative element

section {
  display: grid;
  grid-template-columns: repeat(3, 150px);
  grid-gap: 20px;
  position: relative;
}

div {
  background: blue;
  height: 30px;
}

span {
  background: red;
  z-index: 9;
  position:absolute;
  top:0;
}
<section>
  <div>1</div>
  <span>coucou</span>
  <div>2</div>
  <span></span>
  <div>3</div>
  <span></span>
  <div>4</div>
  <span></span>
  <div>5</div>
  <span></span>
  <div>6</div>
  <span></span>
</section>

or if you don't want span between div you can use display:none

section {
  display: grid;
  grid-template-columns: repeat(3, 150px);
  grid-gap: 20px;
  position: relative;
}

div {
  background: blue;
  height: 30px;
}

span {
  display: none;
}
<section>
  <div>1</div>
  <span>coucou</span>
  <div>2</div>
  <span></span>
  <div>3</div>
  <span></span>
  <div>4</div>
  <span></span>
  <div>5</div>
  <span></span>
  <div>6</div>
  <span></span>
</section>

  • Related