Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max-height AND max-width with CSS only

Tags:

css

image

First post for me here.

I'm using a div to crop thumbnail images all in the same proportions (180wx170h). I'm getting stuck when dealing with portrait as well as landscape images. If am using this which is fine for portrait style images:

.crop img {max-height:170px; width:auto}  

.. and is fine for landscape style images:

.crop img {max-width:180px; height: auto;} is fine for landscape style images.   

So I basically want to crop the sides if landscape and top/bottom if portrait. Kind of like a prioritized max-height and max-width.

I know this could be done easily with PHP but I really only know CSS so that would be my first preference.

I need to maintain the aspect ratio of the image.

like image 560
Andy Blanc Avatar asked Jan 16 '13 02:01

Andy Blanc


People also ask

What is max width and max height in CSS?

The CSS height and width properties are used to set the height and width of an element. The CSS max-width property is used to set the maximum width of an element. This element has a height of 50 pixels and a width of 100%.

Is there max height in CSS?

The max-height property in CSS is used to set the maximum height of a specified element. Authors may use any of the length values as long as they are a positive value. max-height overrides height, but min-height always overrides max-height .

Can we use max width and min width at the same time?

Max-width and min-width can be used together to target a specific range of screen sizes. @media only screen and (max-width: 600px) and (min-width: 400px) {...} The query above will trigger only for screens that are 600-400px wide. This can be used to target specific devices with known widths.


2 Answers

the solutions after going through loads of other 'solutions'

max-width:100%; max-height:100%; height: auto; width:auto; 
like image 165
Nick Avatar answered Oct 11 '22 12:10

Nick


Edit 2019:

If you want to keep <img> tags, please look into object-fit css property, support of it across browsers is quite good.

And if you want to keep aspect ratio on width change, try padding-hack.


As I understand you have blocks 180x170 px and you want to fill them completely with images. Try to move images to background and use background-size:cover.

Demo http://jsfiddle.net/heuku/1/

<div style="background-image:url(http://placekitten.com/100/200)"></div> <div style="background-image:url(http://placekitten.com/200/100)"></div> <div style="background-image:url(http://placekitten.com/200/200)"></div>  div {   width:180px;   height:170px;   background-repeat:no-repeat;   background-size:cover; } 

Note that this solution not working in IE8 and below.

like image 31
antejan Avatar answered Oct 11 '22 14:10

antejan