How to add programmatically region's class when region had block in D8? I have one row three column region. How can I add custom class on each region when one of region is not work?

When three regiosn work, classes will be below

|------------|-------------|--------------|
|            |             |              | 
|  region 1  |   region 2  |    region 3  |
|            |             |              |
|------------|-------------|--------------|
  col-sm-4      col-sm-4       col-sm-4




When two regions work, classes will be below

|-------------------|---------------------|
|                   |                     | 
|  region 1         |     region 2        |
|                   |                     |
|-------------------|---------------------|
      col-sm-6             col-sm6




When only one region work, class will be below

|-----------------------------------------|
|                                         | 
|               region 1                  |
|                                         |
|-----------------------------------------|
               col-sm-12


I use in page.html.twig like below. It worked for me but not good code for more column.

{% if page.region_1 and page.region_2 %}
  &lt;div class="row"&gt;
    &lt;div class="region_1 col-sm-6"&gt; {{ page.region_1 }} &lt;/div&gt;
    &lt;div class="region_2 col-sm-6"&gt; {{ page.region_2 }} &lt;/div&gt;
  &lt;/div&gt;
{% endif %}

{% if not page.region_1 and page.region_2 %}
  &lt;div class="region_2 col-sm-12"&gt; {{ page.region_2 }} &lt;/div&gt;
{% endif %}

{% if not page.region_2 and page.region_1 %}
  &lt;div class="region_1 col-sm-12"&gt; {{ page.region_1 }} &lt;/div&gt;
{% endif %}


I'm try using hook_preprocess_region() like below. Can I check regions condition in hook_preprocess_region?

function MYTHEME_preprocess_region(&amp;$variables) {

  // Add class in header region.
  $region = $variables['elements']['#region'];
  $region_header = array(
    'region_1',
    'region_2',
    'region_3'
  );

  if (in_array($region, $region_header)) {
    $variables['attributes']['class'][] = 'col-sm-12';
  }

}
Check Block Class module for this 

Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!