Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive circular images

I am currently working on creating a dynamic style sheet for myself that I will use in the future, and therefore I want it to be dynamic and not hard coded.

I have an image class:

.image-round{
    border-radius: 50%;
}

This class works nicely for all square images, but when I try rectangular images, I get an oval.

I tried getting around this by using jQuery, wrapping the image in a container, that I made have overflow hidden and set its height and width to be equal to the height of the image. This solved the problem, however now I am facing responsive issues.

When I try to scale the window down, the image becomes squished.

Now I wonder if there is a solution to solve this problem entirely dynamically, with no hard coding what so ever, making images in landscape as well as portrait round.

I really want to avoid having to check the images size on window resize, and then readjusting the containers size - as I am pretty sure this will take a lot of performance.

It is also not an option to use background image.

like image 448
user3385205 Avatar asked Feb 11 '16 10:02

user3385205


1 Answers

You can make all images round by wrapping the images in a div and

  • maintain its aspect ratio to be square (for several techniques to maintain the aspect ratio of a div see here)
  • apply the border-radius and overflow:hidden; on the wrapper.

This will prevent the images to be displayed oval.

Then the issue is handling every image aspect ratio, landscape and portrait so they are centered and "cover" the container. For that you can use the object-fill property like this:

div{
  position:relative;
  width:20%;
  padding-bottom:20%;
  border-radius:50%;
  overflow:hidden;
}
img{
  position:absolute;
  object-fit: cover;
  width:100%;height:100%;
}
<div><img src="http://i.imgur.com/uuEyxxE.jpg" /></div>
<div><img src="http://i.imgur.com/HDssntn.jpg" /></div>

The drawback is that IE doesn't support object-fill. So you need a fallback to handle two cases :

  • landscape images limit the size of image from height
  • portrait images limit the size of image from width

div{
  position:relative;
  width:20%;
  padding-bottom:20%;
  border-radius:50%;
  overflow:hidden;
}
img{
  position:absolute;
  margin:auto;
}
.landscape img{
  height:100%;
  left:-100%; right:-100%;
}
.portrait img{
  width:100%;
  top:-100%; bottom:-100%;
}
<div class="landscape"><img src="http://i.imgur.com/uuEyxxE.jpg" /></div>
<div class="portrait"><img src="http://i.imgur.com/HDssntn.jpg" /></div>

In this configuration, you will need JS to identify landscape or portrait images and style them accordingly.

like image 77
web-tiki Avatar answered Oct 06 '22 08:10

web-tiki