Accueil > Carnet > How to crop an image with CSS

Après plus de 12 années de présence sur le web, je continue encore aujourd'hui cette incroyable aventure qu'est la découverte du virtuel. Lampe torche, sac à dos, planche de surf et bien sûr ce calepin indispensable pour mémoire.

#489 How to crop an image with CSS 13 Mai 2010

css

Butterlies

You know the dimensions of your container but you don't know the size of your image: you will have to make a crop. My little trick will work with a container and the image inside.

It's a small css trick where I am using the CSS2 property clip. Let's say: you want to have a container with defined proportions: 240x300, a 4-pixels padding and a light blue border around. One more time: you don't know the size of your image and it can varies.

HTML

<span><img src="yourimage.jpg" alt="description" /></span>

CSS

span {
	display: block;
	position: relative; 
	overflow: hidden;
	width: 240px; 
	height: 300px; 
	padding: 4px; 
	border: 1px solid lightblue;
	background: lightyellow;
}
 
img {
	position: absolute;
	min-width: 240px; 
	min-height: 300px; 
 
	// Parameters: 
	// 4px: padding-top 
	// 232px: width-2*padding (top+bottom)
	// 292px: height-2*padding (top+bottom)
	// 4px: padding-left 
	clip: rect(4px, 232px, 292px, 4px);
	_clip: rect(4px 232px 292px 4px); // For IE6 
}

If you know which side of your image will be wider, it's easier to scale then to crop. Here, we're just making sure the image will have at least the dimension of the container. This solution can be better, that's just a draft for now :)

Commentaires

Ajouter un commentaire