Andrew
Andrew

Reputation: 2114

How to match height of an image to sibling content and maintain image aspect?

I want to make a layout for a notification card, like this:

Mockup

Which obeys the following layout rules:

I've been through flexbox, floats, absolute positioning hacks, and I can't think of a single way to achieve this. Help! If it makes it easier, I'd settle for requiring the image to be square.

Upvotes: 1

Views: 639

Answers (2)

Jonathan
Jonathan

Reputation: 1564

I managed to get round the scaled background image on my site by using the background-size:cover property combined with a centered, fixed background image on the containing element

The trick for you would be to set the image as a background of, for example, a div and automatically size that div for the space available

here is a jsfiddle: http://jsfiddle.net/20v1mgr0/1/

Markup would be something like this:

<div class="hero-unit table">
    <div class="table-row">
        <div class="width-one table-cell scaled-image"></div>
        <div class="width-two table-cell text-area">
            <h2>Text goes in here</h2>
            <p>Text goes in here</p>
        </div>
    </div>
</div>

Style would be something like this:

.table{
    position: relative;
    display:table;
}
.table-row{
    position: relative;
    display:table-row;
}
.table-cell{
    position: relative;
    display:table-cell;
}
.hero-unit{
    width:600px;
    padding:20px;
    background:yellow;
    margin-bottom:20px;
}
.scaled-image { 
    background: url('https://i.sstatic.net/jGlzr.png') no-repeat center center; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    border:1px solid green;
}
.text-area{
    background:blue;
}
.width-one {
    width:20%;   
}
.width-two {
    width:80%;
    padding:0 20px;
}

Upvotes: 3

Oriol
Oriol

Reputation: 288010

I guess that if image's width increases, it must push the text to the right to avoid overlapping it, right?

But then there is less space for text, which may require an additional line. So image's height will increase to match the new height of the text, and its width too to maintain aspect ratio.

But then there will be even less space for text, and so on.

So I guess your layout rules are defined recursively, and therefore you can't achieve it.

Upvotes: 3

Related Questions