Chris
Chris

Reputation: 1050

Aligning div with background image of parent div

I have two div's, one over the other. The bottom div has a background image with two columns, one at 40% width and the other 60%

    .container.style-2 {
        background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAC7gAAAABAQMAAAB0GXF9AAAABlBMVEX////09PQtDxrOAAAAD0lEQVQY02P4PygBw3AHAG6mlWu52WYpAAAAAElFTkSuQmCC');
        background-repeat: repeat-y;
        background-position: 40% 0; 
    }

    .container.style-2:before {
        height: 100px;
        width: 100%;

        margin-top: -100px;
        position: absolute;
        content: '';
        background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAC7gAAAABAQMAAAB0GXF9AAAABlBMVEX////09PQtDxrOAAAAD0lEQVQY02P4PygBw3AHAG6mlWu52WYpAAAAAElFTkSuQmCC');
        background-repeat: no-repeat;
        background-position: 40% 0; 
    }

    .container.style-2:after {
        height: 150px;
        width: 100%;

        position: absolute;
        content: '';
        background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAC7gAAAABAQMAAAB0GXF9AAAABlBMVEX////09PQtDxrOAAAAD0lEQVQY02P4PygBw3AHAG6mlWu52WYpAAAAAElFTkSuQmCC');
        background-repeat: no-repeat;
        background-position: center; 
        background-position: 40% 0; 
    }

The top div has a max width at 600px and inside two div columns, one at 40% width and the other 60%

    .container .row .col-1, .container .row .col-2 {
        display: inline-block;
        float: left;
    }

    .container .row .col-1 {
        width: 40%;
        background-color: #00ffff;
    }

    .container .row .col-2 {
        width: 60%;
        background-color: #ff0000;
    }

If the browsers window width is at 600px or less, the background image and div column align perfectly but any wider the two begin to misalign.

Is it possible to align the top and bottom div columns?

Please see this CodePen

Thanks for any help

Upvotes: 3

Views: 836

Answers (1)

ryantdecker
ryantdecker

Reputation: 1810

http://codepen.io/ryantdecker/pen/zBoNWK

CSS calc to the rescue - along with a media query.

@media (min-width:601px) {
  .style-2:before,
  .style-2:after {
    background-position: calc(50% + 240px);}
}

Once the max-width:600px; takes over on your .row, and your content columns start to be center aligned (as a group), so you need to also have your background relative to the center of the page/wrapper (the 50% in calc) so that they will stay positioned consistently in relation to each other.

However, your columns aren't equal, so you actually want the image to be offset from the center a static amount (not a % of the parent's width, which will change even when the columns aren't changing), which is where calc comes in -- 240px is the width of your small column, which also happens to be how far from center you need to keep your image for it to line up.

Upvotes: 2

Related Questions