I'm creating a variant of the well-known media object which meets the following criteria:
I'm using the age-old display: table
/ table-cell
approach as such:
<div class="o-media">
<div class="o-media__img">
<!-- begin picture component -->
<div class="c-picture">
<div class="c-picture__container">
<picture class="c-picture__el">
<source media="(min-width: 1024px)" srcset="https://www.topoutshoes.com/media/catalog/product/cache/1/image/1200x1200/9df78eab33525d08d6e5fb8d27136e95/_/1/_11_1_7.jpg" class="c-picture__source">
<img src="http://shopshoeguru.com/sites/default/files/image/shoeguru-banner-red.png" class="c-picture__img _o-media__image--overview-01" alt="Overview 1 photo">
</picture>
</div>
</div>
<!-- end picture component -->
</div>
<div class="o-media__body">
<!-- some copy and such -->
</div>
</div>
And the CSS:
* {
border: 1px solid red;
}
.o-media {
height: 550px;
}
.o-media__body {
height: 50%;
}
.o-media__img {
height: 50%;
}
._o-media__image--overview-01 {
/* want to be able to set this using percentage! */
height: 200px;
}
.c-picture {
display: table;
width: 100%;
height: 100%;
}
.c-picture__container {
display: table-cell;
vertical-align: middle;
}
.c-picture__el {
display: inline-block;
}
.c-picture__source {
display: none;
}
.c-picture__img {
display: block;
}
Here's a jsfiddle of this code in action: https://jsfiddle.net/v9gf3c9a/
The issue, as noted by my comment within the CSS, is that I have to explicitly set the height of the img
, as it won't respect percentage-based heights, due to the use of display: table
and display: table-cell
. If I use regular-old display
values, such as block
and inline-block
, a percentage on the img
works fine.
Is there any way to achieve this so that I can use a percentage on the img
, but still use vertical-align
via display: table
/ table-cell
?
How about this:
* {
border: 1px solid red;
}
.o-media {
height: 550px;
}
.o-media__body {
height: 50%;
}
.o-media__img {
height: 50%;
}
._o-media__image--overview-01 {
/* want to be able to set this using percentage! */
height: 100%;
position: absolute;
}
.c-picture {
display: table;
width: 100%;
height: 100%;
}
.c-picture__container {
display: table-cell;
vertical-align: middle;
height: 100%;
}
.c-picture__el {
display: inline-block;
position: relative;
height: 80%;
}
.c-picture__source {
display: none;
}
.c-picture__img {
display: block;
height: 100%;
}
Alternatively you could use flexbox, with align-items: center;
on the flex container.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.