bootstrap-4

How to set Bootstrap 4 column width relative to parent div


I am using Bootstrap 4 and am trying to create a simple layout. Two columns, split into 9 columns and 3 columns. Inside the first column is just text. But I need a padding of 1 column. Not 1 column of the containing div, but one column of the entire page. Here is an example

Desired layout using bootstrap 4

My code below obviously doesn't work. The 1 column padding is 1 column of the containing div.

.left-box {
    background: lightgray;
    text-align: justify;
}

.right-box {
    background: darkgray;
    height: 100px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
    <div class="row">
        <div class="col-9">
            <div class="left-box py-1">
                <div class="col-10 offset-1">
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec volutpat sapien. Suspendisse erat ex, condimentum et faucibus et, ornare in elit. Mauris eget lacinia sapien. Proin eu porttitor odio.</p>
                </div>
            </div>
        </div>
        <div class="col-3">
            <div class="right-box"></div>
        </div>
    </div>
</div>

This gives the following result, where the padding is incorrect.

columns with incorrect padding

Is there a way to achieve the correct padding?


Solution

  • You can calculate the necessary padding-left, calc(8.333% + 15px) - 100% / 12 columns gives us the 8.333%, plus the 15px column-gutter.

    .left-box {
        background: lightgray;
        text-align: justify;
        padding-left: calc(8.333% + 15px) !important;
    }
    
    .right-box {
        background: darkgray;
        height: 100px;
    }
    
    .test .col-1 { height: 1em; outline: 1px solid red; }
    
    
    .test .col-1 div { outline: 1px solid blue; }
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container">
      <div class="row test">
        <div class="col-1"></div>
        <div class="col-1"><div>
        foo
        </div></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
        <div class="col-1"></div>
      </div>
      <div class="row">
        <div class="col-9 left-box" style="background:#ccc">
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec volutpat sapien. Suspendisse erat ex, condimentum et faucibus et, ornare in elit. Mauris eget lacinia sapien. Proin eu porttitor odio.</p>
        </div>
        <div class="col-3">
          <div class="right-box"></div>
        </div>
      </div>
    </div>