tleef
tleef

Reputation: 3594

Center crop img to fill div

I have a three column Holy Grail layout were the width of the left and right columns are fixed and the center column is fluid. The height of the layout is defined by the center column's contents. In the right column I need a full bleed center cropped image. That's the hard part. I have a sample of what I'm going for here but I'm explicitly defining the height of the image to be 180px and I'd like for it to simply grow to the height of the center column. Also, I'd like to avoid using javascript if at all possible and its not necessary to use flexbox, that's just the best I could come up with so far.

Upvotes: 0

Views: 338

Answers (1)

haxxxton
haxxxton

Reputation: 6442

Unless you explicitly need to use an <img> tag you could use an inline css styles to control the background-image of the div rather than placing as an element within the div

For example:

<div class="container">
    <div class="col1"></div>
    <div class="col2">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec rhoncus orci, eget eleifend risus. Maecenas suscipit arcu et aliquet tristique. Quisque venenatis est a maximus consectetur. Nam id fringilla odio. Mauris lobortis nec lorem nec congue. Maecenas elit risus, vestibulum vitae quam eu, ultrices condimentum dolor. Mauris magna nulla, congue eu enim a, fringilla cursus elit. Nulla tempor finibus eleifend. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
    </div>
    <div class="col3">
        <div class="fill" style="background-image:url('http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Mona_Lisa_headcrop.jpg/36px-Mona_Lisa_headcrop.jpg');">
        </div>
    </div>
</div>

then using some CSS you can control the center'ed and fullness of the image. NOTE: I assume that CSS3 styles are ok for your implementation given you are currently using flex-box

.container {
    display: flex;
    flex: 1;
}

.col1 {
    background-color: hotpink;
    order: 0;
    flex: 0 0 50px;
}

.col2 {
    background-color: deepskyblue;
    order: 1;
    flex: 1;
}

.col3 {
    background-color: hotpink;
    order: 3;
    flex: 0 0 70px;
    position:relative;
}

.fill {
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-repeat:no-repeat;
    background-size:cover;
    background-position:center center;
}

Upvotes: 1

Related Questions