How can I display just a portion of an image in HTML/CSS?
As mentioned in the question, there is the clip
css property, although it does require that the element being clipped is position: absolute;
(which is a shame):
.container {
position: relative;
}
#clip {
position: absolute;
clip: rect(0, 100px, 200px, 0);
/* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */
}
<div class="container">
<img src="http://lorempixel.com/200/200/nightlife/3" />
</div>
<div class="container">
<img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />
</div>
JS Fiddle demo, for experimentation.
To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path
, which has replaced the now-deprecated clip
property.
The clip-path
property allows a range of options (more-so than the original clip
), of:
-
inset
— rectangular/cuboid shapes, defined with four values as 'distance-from'(top right bottom left)
. -
circle
—circle(diameter at x-coordinate y-coordinate)
. -
ellipse
—ellipse(x-axis-length y-axis-length at x-coordinate y-coordinate)
. -
polygon
— defined by a series ofx
/y
coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point:polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...])
. -
url
— this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.
div.container {
display: inline-block;
}
#rectangular {
-webkit-clip-path: inset(30px 10px 30px 10px);
clip-path: inset(30px 10px 30px 10px);
}
#circle {
-webkit-clip-path: circle(75px at 50% 50%);
clip-path: circle(75px at 50% 50%)
}
#ellipse {
-webkit-clip-path: ellipse(75px 50px at 50% 50%);
clip-path: ellipse(75px 50px at 50% 50%);
}
#polygon {
-webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);
clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);
}
<div class="container">
<img id="control" src="http://lorempixel.com/150/150/people/1" />
</div>
<div class="container">
<img id="rectangular" src="http://lorempixel.com/150/150/people/1" />
</div>
<div class="container">
<img id="circle" src="http://lorempixel.com/150/150/people/1" />
</div>
<div class="container">
<img id="ellipse" src="http://lorempixel.com/150/150/people/1" />
</div>
<div class="container">
<img id="polygon" src="http://lorempixel.com/150/150/people/1" />
</div>
JS Fiddle demo, for experimentation.
References:
-
— note: deprecated.clip
-
clip-path
(MDN). -
clip-path
(W3C).
One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.