html - How do I y-center an image ON CLIP but let it stay top aligned if it is smaller than its container? -


i have container holds image. image fills container horizontally , container responds page size. see fiddle:

im html

<div id="container">   <img src="http://silberschauer.de/img/pre/045.jpg" /> </div> 

in css

#container {position:absolute;top:1em;left:1em;bottom:2em;  width:30%;background:#0f0;overflow:hidden;} #container img {width:100%;} 

https://jsfiddle.net/t4um60k1/8/

is possible have image clip top , bottom equally if (and if) container gets smaller in y-axis image css?

edit: did not understand question if solution provides green area above image in circumstances.

is possible have image clip top , bottom equally while staying top-aligned if container gets smaller in v-axis image css?

yes, can done neatly , efficiently css. flexbox well-suited sort of thing.

no need js. no changes html.

add css:

#container {     display: flex;                   /* new */     flex-direction: column;          /* new */     justify-content: space-between;  /* new */     position: absolute;     top: 1em;     left: 1em;     bottom: 2em;     width: 30%;     background: #0f0;     overflow: hidden; }  #container::before, #container::after {     content: ''; }  #container img {     width: 100%;     flex-shrink: 0; } 

https://jsfiddle.net/t4um60k1/10/


explanation

we use flexbox align image on vertical axis (flex-direction: column).

then tell flex container child elements (aka, flex items) align space-between.

with justify-content: space-between, flex items evenly spaced, first item aligned @ 1 edge of container , last item aligned @ opposite edge. in case, because we're in column direction, we're talking top , bottom edges.

to ensure image stays in middle, create "phantom" flex items on each end using pseudo-elements.

but why take these steps center image, when justify-content: center have done job less hassle?

because second requirement of question image must top-aligned when exceeds height of container.

with justify-content: center image stay centered @ times.

but under rules of space-between, if flex items overflow container, space-between switches flex-start, aligns image top (more details below).

lastly, flex items flexible, flex-shrink: 0 applied image ensure doesn't shrink original size.


switching space-between flex-start

from spec:

space-between

flex items evenly distributed in line. if leftover free-space negative or there single flex item on line, value identical flex-start.

center

flex items packed toward center of line. ... if leftover free-space negative, flex items overflow equally in both directions.

(emphasis mine)

source: https://www.w3.org/tr/css-flexbox-1/#justify-content-property


note flexbox supported major browsers, except ie 8 & 9. recent browser versions, such safari 8 , ie10, require vendor prefixes. quick way add prefixes need, post css in left panel here: autoprefixer.


Comments