2

I am using Ionic 1.x and Angular 1.x, I display an avatar image thats usually square but not always, I want it to be full width, and then square, so if the screen is 720px wide, I want a 720px tall and wide image, if the image is larger than this size, it should hide the excess (ideally in a smart way).

I have only included the ionic styles, and a few of my own, so bootstrap isnt included in this project.

I would be happy applying a class with width: 100% to the image, and a height: auto, but the height should not be more than the width.

As mentioned it needs to be responsive as it will be shown on a variety of screen sizes, so the image I wont always know to set the size for... I could use some JS to manually calculate and set the sizes, but is that not a bit clunky?

I had a look for directives but could find none.

dhj
  • 4,780
  • 5
  • 20
  • 41

1 Answers1

0

One way to do this is to create a responsive square element and then use a CSS background image rather than an HTML img src:

  • You can make a responsive element of any given aspect ratio with height: 0, width: x%, and padding-bottom: y% (or padding-top), where x/y is the aspect ratio. (This works because percentage padding is relative to width). In your case, to make a full-width square use height: 0; width: 100%; padding-bottom: 100%;.

  • Because you're using an <img>, you'll get a "missing image" outline that can't be removed with CSS. Hack around this by using a single transparent pixel as your src image. Base64 encoded, that's src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" (thanks to Chris Coyier for saving us the trouble of making our own)

  • Now add your image as an inline background-image. Center it with background-position: center, and use background-size: cover to make scale to fit the <img>. You can use the background shorthand to say that in one CSS property, with background: position/size.


Here it is all together. I'm using a wrapper element just to make things fit in the snippet results window; the second image demos successfully turning a non-square image into a square.

img {
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  background: no-repeat center/cover;
}
#wrapper-for-demo {
  width: 200px;
}
<div id="wrapper-for-demo"><!-- just to fit nicely in the stacksnippets results window -->
  
  <!-- an image with a square source -->
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" style="background-image:url(http://placehold.it/400x400)" />
  
  <!-- an image with a non-square source -->
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" style="background-image:url(http://placehold.it/400x600)" />
  
</div>
Community
  • 1
  • 1
henry
  • 4,244
  • 2
  • 26
  • 37