Search code examples
cssbootstrap-4gridrow

Bootstrap : Add a junction between div


enter image description hereI'm trying to add a junction (a line) between 2 divs in the middle.

<div class="row">                   
<div class="col-xs-6 col-md-6">
    <div style="background-color:#f39a6f;width:100%;height:100px;">
    ....1
    </div>
</div>  
<div class="col-xs-6 col-md-6">
    <div style="background-color:#ffff00;width:100%;height:100px;">
    ....2
    </div>
</div>      

Thanks for help.


Solution

  • My idea is to have the junction (a line) always be the center of a row via absolute/relative positioning, with lower z-index than what those color blocks have so that the line is hidden behind the blocks but shown between the blocks.

    The tricky part is accurately calculate the position of the junction line, due to the fact that bootstrap rows have their own paddings. That's why it's better to use SCSS so that you can read bootstrap default values for row and column settings, and calculate the junction line based on those.

    But for demo purpose, I will stick with CSS and "hardcode" the pre-configured values from bootstrap.

    HTML Structure

    <div class="row junction-row">
        <div class="col-6 col-sm-3">
            <div class="block bg-primary"></div>
        </div>
        </div class="col-6 col-sm-4 offset-sm-5">
            <div class="block bg-danger"></div>
        </div>
    </div>
    

    CSS

    .junction-row {
        height: 6rem;
        position: relative;
    }
    
    .junction-row::after {
        content: '';
        position: absolute;
        background-color: var(--danger);
        height: 5%;
    
        // Default bootstrap row's padding is 1rem.
        // Width = 100% - left padding of the row - right padding of the row
        width: calc(100% - 2rem);
    
        // Top = total height 100% - the height of the line, and then divide by 2
        // to have the line stay in the center of the row.
        top: calc((100% - 5%) / 2);
    
        // Left = starting after the row's left padding
        left: 1rem;
     
        // Any value here, but it needs to be lower than what .block has
        z-index: 1;
    }
    
    .block {
        position: relative;
        height: 6rem;
        z-index: 2;
    }
    

    Result

    enter image description here

    enter image description here

    demo: https://jsfiddle.net/davidliang2008/vknor3cz/32/