amlyhamm
amlyhamm

Reputation: 1150

Change only the width of an image (css only)

I have an image (say 150 x 300), and I want to change just the width to 1 pixel but want the image to maintain its original height of 300 pixels (there is actual logic to this end goal, I swear). So my final image would be 1 x 300.

Of course this should be as easy as:

img {
    width:1px;
    height:300px;
}

But the tricky part is, I don't know the height of the image. This image is dynamic and could have any dimensions. How can I force CSS to ignore the aspect ratio and make the height maintain its initial value? I know this would be quite easy with jQuery, but I'd like to accomplish it with CSS alone. Any ideas?

Thanks in advance!

Upvotes: 2

Views: 4111

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123438

In pure CSS you may use clip in conjunction with position: absolute

img {
  position: absolute;
  clip: rect(0px 1px auto 0);
}

Example: http://codepen.io/anon/pen/siyDe

As you can see, you don't need to specify the height of the image (auto does the trick). In a real page you would probably need to enclose the image in a container with position: relative

Upvotes: 1

moongoal
moongoal

Reputation: 2966

If you mean "resize the image WITHOUT taking into account the aspect ratio", you can set the CSS3's object-fit property of the image to object-fit: fill.

img {
  width: 1px;
  object-fit: fill;
}

Upvotes: 1

LeBen
LeBen

Reputation: 2049

If the height attribute is defined on your image, your can simply achieve it with this CSS:

img {
  width: 1px;
}

http://jsfiddle.net/yvr57/

Upvotes: 3

Related Questions