Reputation: 844
I want to add rounded corners to my images. They are Bootstrap 4 responsive images (With the class img-fluid
), so I don't want to use something like border-radius=15px
, because if the images become very small (on a small viewport), the rounded off corners will take up most of the image, and when the images are very large, the rounding will be barely notiecable.
I can use border-radius=15%;
, but if my image is not a square, the rounded corners are elliptical instead of circular. I can fix this with border-radius=15%/10%;
, but then I have to adjust this ratio to match the aspect ratio of each individual image.
Is there a way to round the corners of a Bootstrap 4 responsive image, such that the rounding is always circular, and always the same ratio of the image width or height, regardless of the aspect ratio of the image?
I would prefer to do this with only CSS. I could do it using Javascript, but I will only really have three different aspect ratios of image in this application, so it would be easier to just create three different classes.
Upvotes: 6
Views: 2551
Reputation: 1941
A hacky solution, but we can use CSS3 vw
or viewport width to achieve something close to what you want. border-radius:5vw;
will reduce or increase the % based on the total width of the viewport.
The size of the image wont matter just the viewport. But you can get pretty good results none the less.
div{
background-color:red;
width:50%;
height:100px;
border-radius:5vw;
}
<div></div>
I suggest you just use JS for this.
Upvotes: 3
Reputation: 12590
Javascript solution
Here is your 15% border radius with the help of some javascript (jQuery):
$(window).resize( function() {
$('img').each(function(){
$(this).css('border-radius',($(this).width()*0.15)+'px');
});
});
$(document).ready( function() {
$(window).resize();
});
https://codepen.io/anon/pen/mqepMQ
PS. I would add a 'standard' border-radius to the image with CSS (e.g. '30px'), so that the image appears roughly correct before the $(document).ready()
kicks in.
Non-javascript solution
Wrap the image in a container and use the before and after pseudo elements on the image and the container to overlay 4 rounded corner images on the image. This assumes and requires that the background is a solid color. These images (preferably SVG) should be/are squares, so it is easy to size them by manipulating just their width. This width can be set relative to the image width (by using a percentage).
Personally I think that this solution is quite messy, due to the extra DOM elements and the images with the fixed background colors. I would choose the javascript solution for its simplicity.
Upvotes: 0