Search code examples
cssbootstrap-4grid-layout

Is it possible to apply CSS style to the whole row inside column?


Using Bootstrap 4 Grid system, I have the following structure: https://i.sstatic.net/MB2C7.png

I have the content column and two blank columns inside each row. Sometimes I need to apply CSS style to the whole row.

<div class="container">
  <div class="row">
    <div class="col-sm-3"></div>
    <div class="col-sm-6">
      Lorem ipsum
    </div>
    <div class="col-sm-3"></div>
  </div>

  <div class="row">
    <div class="col-sm-3"></div>
    <div class="col-sm-6">
      dolor sit amet,
    </div>
    <div class="col-sm-3"></div>
  </div>
  ....
  <div class="row custom-background-color">
    <div class="col-sm-3"></div>
    <div class="col-sm-6">
      consecteur adipiscing elit,
    </div>
    <div class="col-sm-3"></div>
  </div>
</div>

But in the same time it becomes not handy to have multiple duplicate code. I want to regroup the code, to have column definition only once.

<div class="container">
  <div class="row">
    <div class="col-sm-3"></div>
    <div class="col-sm-6">
      <div class="row">Lorem ipsum</div>
      <div class="row">dolor sit amet,</div>
      ...
      <div class="row custom-background-color">consecteur adipiscing elit,</div>
    </div>
    <div class="col-sm-3"></div>
  </div>
</div>

I expect to have the CSS style not for one column, but for the whole page width. Is it possible to make a workaround or find solution to solve the problem?


Solution

  • Yes it is possible if you have the same amount of rows in each column. Then, you can use the nth-child selector to pass styles to e.G. the fifth row in each column.

    div[class^="col"] .row:nth-child(2) {
        background: green;
    }
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container">
      <div class="row">
        <div class="col-sm-3">
         <div class="row">ipsum</div>
          <div class="row"> amet,</div>
          <div class="row"> elit,</div>
        </div>
        <div class="col-sm-6">
          <div class="row">Lorem ipsum</div>
          <div class="row">dolor sit amet,</div>
          <div class="row">consecteur adipiscing elit,</div>
        </div>
        <div class="col-sm-3">
         <div class="row">Lorem ipsum</div>
          <div class="row">dolor</div>
          <div class="row">consecteur</div></div>
      </div>
    </div>