So this is what I want to do :
I have a regular rectangle image, and I want to be displayed as a rounded image. How can I do this?
(Image credit)
I hope I got this right:
you have a rectangular non-square image, something like this
(width > height) or like this
(height > width)
and you want to display it in a circle without distorting it,
probably as much as you can display of it and the central part,
something like this:
Solutions:
When you know the size of the image it is really simple: you put it in a wrapper, give a wrapper a width and a height that are both equal to the minimum between the width and the height of the image itself. You then give the wrapper border-radius: 50%; and overflow: hidden;.
Next, you position the image such that the central part is visible.
if the width of the image is greater than its height (landscape
image), then you set its left margin to be (height-width)/2
otherwise, if the height of the image id greater than its width
(portrait image), then you set its top margin to be (width-height)/2
demo
Relevant HTML:
<a href='#' class='circle-wrap'>
<img src='image.jpg'>
</a>
Relevant CSS for landscape image (dimensions: 468px x 159px):
.circle-wrap {
overflow: hidden;
width: 159px; height: 159px; /* height of img */
border-radius: 50%;
}
.circle-wrap img {
margin: 0 0 0 -154px; /* (height-width)/2 */
}
Alternatively, you could use a JavaScript solution (I'm suggesting this because you list javascript among the tags) if you don't know anything about the orientation (portrait or landscape) of your image or about its dimensions.
demo
I've used a few images of different orientations sizes for testing. The HTML for one:
<a class='circle-wrap' href='#'>
<img src='image.jpg'>
</a>
Relevant CSS:
.circle-wrap {
overflow: hidden;
padding: 0;
border-radius: 50%;
}
.circle-wrap img { display: block; }
JavaScript:
var wrps = document.querySelectorAll('.circle-wrap'),
toCircle = function(a) {
var style, w, h, img;
for(var i = 0; i < a.length; i++) {
style = window.getComputedStyle(a[i]);
w = parseInt(style.width.split('px')[0],10);
h = parseInt(style.height.split('px')[0],10);
/* part that makes the wrapper circular */
a[i].style.width = a[i].style.height = Math.min(w,h)+'px';
/* part that takes care of centering imgs */
img = a[i].querySelector('img');
if(w > h)
img.style.marginLeft = ((h - w)/2) + 'px';
else if(w < h)
img.style.marginTop = ((w - h)/2) + 'px';
}
};
toCircle(wrps);
Try
img { border-radius:50%; }
Note that the image must have equal width and height for this to work. If the image doesn't, you can set the width and height with CSS as well.
img { border-radius:50%; width:200px; height:200px; }
Fiddle
All you need is CSS to do this:
<img class='circle' src='/my/img/path/img.jpg' />
<style type="text/css">
img.circle {
-ie-border-radius: 50%; /* IE */
-khtml-border-radius: 50%; /* KHTML */
-o-border-radius: 50%; /* Opera */
-moz-border-radius: 50%; /* Mozilla / FF */
-webkit-border-radius: 50%;/* Chrome / Safari */
border-radius: 50%; /* CSS Compliant */
}
</style>
Have a white square image with a transparent circle in the middle and overlay on the image.
Related
I'm using a full screen canvas as background of the first section of my page. But as soon as I add the second section and vertical scrollbar appears, the height of canvas reduces a little bit and a gap appears. here's my code:
P.S: Sorry, my code contained bugs, I fixed them. now you can see the red gap.
var canvas = document.getElementById('canvas')
var c = canvas.getContext('2d')
scaleCanvas()
window.addEventListener("resize", scaleCanvas)
function scaleCanvas() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
c.fillStyle = 'black'
c.fillRect(0, 0, canvas.width, canvas.height)
}
* {
box-sizing: border-box;
max-width: 100%;
}
body {
margin: 0;
padding: 0;
}
#first-section {
position: relative;
min-height: 100vh;
background-color: red; /* to see the gap */
}
#content {
position: relative;
z-index: 2;
}
#second-section {
min-height: 100vh;
background-color: blue;
}
#canvas {
display: block;
padding: 0;
margin: 0;
border: none;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
<div id="first-section">
<canvas id="canvas"></canvas>
<div id="content">content</div>
</div>
<div id="second-section"></div>
Assuming you mean full screen, and not full page. The two are very different.
If you mean full page then the link to the Screen API will also give you details on obtaining the page size.
Size full screen canvas.
The problem is that you have content that extends outside the page width and height (innerWidth, innerHeight)
The elements with ids first-section, content, and second-section must be inside the display area or else you will get a scroll bar. The scroll bar will change the innerWidth, innerHeight values subtracting the scrollbar width or height depending on which is visible.
To prevent scroll bars the best option is to keep all content inside innerWidth, and innerHeight
Full screen with scroll bars.
If you want have the scroll bars and you are using full screen you can use the Screen API to get the width and height of the display in pixels. You can set the canvas size to match the screen without the scroll bars effecting its size.
Note Do read the provided link to Screen as what defines the screen may not be as expected. EG more than one monitor, or device orientation will effect how you use the API.
Basic example
Thus when in full-screen mode you can set the canvas size and ignore scroll bars with
function sizeFullScreenCanvas() {
canvas.width = screen.width;
canvas.height= screen.height;
}
I use images created on the fly to maintain the aspect ratio of boxes with a fixed height. Image sources are set as data-urls provided from a canvas with a given width and height, the images are then attached to divs which can contain any content, have any height, and still maintain a fixed aspect ratio.
This works well, however, on slower phones with less memory the large number of data-urls on the page can start to be a little bit of a drag. Some of the ratios can't be reduced below a certain point resulting in relatively large canvases.
Is there any way to set the ratio of an img element without setting its source? Is there any way to set the source to a format that is an truly empty image with only a width and height?
EDIT: The snippet below throws an error - iframe restrictions, probably having to do with making images. You can see an error free version over at this CodePen.
const wrapper = document.querySelector(".wrapper");
function addRatioBox(width, height = 1) {
const cvs = document.createElement("canvas");
const img = new Image(width, height);
const box = document.createElement("div");
cvs.width = width;
cvs.height = height;
img.src = cvs.toDataURL("image/png");
box.appendChild(img);
box.className = "ratioBox";
wrapper.appendChild(box);
}
addRatioBox(1);
addRatioBox(4, 3);
addRatioBox(16, 9);
addRatioBox(2, 1);
.ratioBox {
background: orange;
display: inline-block;
height: 100%;
margin-right: 10px;
}
.ratioBox img {
height: 100%;
width: auto;
display: block;
}
/* just a whole bunch of stuff to make things prettier from here on down */
.wrapper {
background: #556;
padding: 10px;
position: absolute;
height: 20%;
top: 50%;
left: 50%;
white-space: nowrap;
transform: translate(-50%, -50%);
}
body {
background: #334;
}
.ratioBox:last-of-type {
margin-right: 0;
}
<div class="wrapper"></div>
After 4 hours of trial and errors, I cannot find a way to get the width of the circle that is defined by a percent and convert it to pixels and make the circles height the same size as the width in pixels. Below is what I have right now. (I have tried many variations of this but cannot figure it out) Right now it only works on my screen. I try it on other devices and the height is just not right. This button is created onload.
Example: Circle Width = 12% , the Pixel Value of 12% on a screen is "70px". So somehow make Circle Height = 70px.
<!DOCTYPE html>
<head>
<title>Circle Test</title>
<meta charset='UTF-8'>
<script type="text/javascript" src="/js/fs"></script>
</head>
<body>
</body>
</html>
// Creates a button
var mainButton = document.createElement("button");
mainButton.style.width = "10%";
// Get the Screens Avaliable Width and Get 10% of it and convert it to pixels
var wad = screen.availWidth * .1 + "px";
// Thinking this would return the pixel amount the circle button is, but it only works on the regular screen and not when resized. It also does not work for mobile.
console.log(wad);
mainButton.style.height = wad;
You set the width of your button to 10% of its containing block's width, and the height to 10% of the width of one of
The available area of the rendering surface of the output device, in CSS pixels.
The area of the output device, in CSS pixels.
The area of the viewport, in CSS pixels.
It's very likely that these are measurements of two different things, or that resizing the window will affect one but not the other. Fortunately, CSS has a unit for "percentage of the window's width": vw. Set your button's height and width in vw units, and you don't need any JavaScript:
button {
width: 10vw;
height: 10vw;
border-radius: 50%;
}
<button>Go</button>
If you really meant that the button is 10% as wide as its container, even if its container isn't as wide as the whole window, you can use the padding-bottom technique detailed in this answer. Unlike height, percentages in padding refer to the width of the containing block:
.wrapper {
width: 40%; /* here I use 40% instead of 10% for aesthetics */
padding-bottom: 40%; /* should match width */
position: relative;
}
.wrapper > button {
display: block;
position: absolute;
width: 100%;
top: 0;
bottom: 0;
border-radius: 50%;
}
/* the rest is just to make figuring out
the exact width of the button difficult */
body {
display: flex;
align-items: stretch;
height: 90vh;
}
body > div {
flex: 1 1 0;
background: rebeccapurple;
margin: 0 4px;
}
<div>
<div class="wrapper"><button>Go</button></div>
</div>
<div></div>
<div></div>
And finally, just for completeness, if you really must get the computed width from JavaScript, you can use window.getComputedStyle:
let button = document.querySelector('button');
let width = window
.getComputedStyle(button)
.getPropertyValue('width');
console.log(button.style.height = /* DO NOT DO THIS */ width);
button {
width: 40%;
border-radius: 50%;
}
/* the rest is just to make figuring out
the exact width of the button difficult */
body {
display: flex;
align-items: stretch;
height: 90vh;
}
body > div {
flex: 1 1 0;
background: rebeccapurple;
margin: 0 4px;
}
<div>
<button>Go</button>
</div>
<div></div>
<div></div>
If you try putting that into a resize handler, though, performance will suffer.
I have a div that has a fixed size of 500x500. Inside this div I have an image tag which can be dynamic. Meaning that it can have a size of a square, a rectangle (width > height), or a vertical rectangle (height > width). The issue is that I don't want this image to be squished, I wanted to keep the aspect ratio of the image. So say the image size is 1000x250, then I want it to be resized as 500x125 and then centered on this 500x500 box. If the size is 500x1000 then we wanted it to be resized as 250x500 and then centered with white spacing on the left and right.
Is there an easy way to do this using purely css or do I need javascript in order to do this? and how?
Here's the structure of what I have now:
<div class="product-large" style="position: relative; overflow: hidden;"><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" alt=""><img src="/images/store_logos/9ae3d8f75c80d5a48bf59f975e8450c9e8b7a9d9.jpeg" class="zoomImg" style="position: absolute; top: -236.43249427917618px; left: -188.05491990846681px; opacity: 0; width: 1024px; height: 714px; border: none; max-width: none;"></div>
Updated for vertical centering - jQuery required.
HTML
<div class="product-large">
<img src="image1.jpg">
</div>
<div class="product-large">
<img src="image2.jpg">
</div>
CSS
.product-large {
width:500px;
height:500px;
border:1px red solid;
position:relative;
}
.product-large img {
max-width:500px;
max-height:500px;
width:auto;
height:auto;
position:absolute;
top:50%;
left:50%;
}
Javascript (jQuery)
$(".product-large img").each(function () {
//get height and width (unitless) and divide by 2
var hWide = ($(this).width()) / 2; //half the image's width
var hTall = ($(this).height()) / 2; //half the image's height, etc.
// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
hTall = '-' + hTall + 'px';
$(this).addClass("js-fix").css({
"margin-left": hWide,
"margin-top": hTall
});
});
New Fiddle: http://jsfiddle.net/Asvdk/2/
I think you can do:
#conatiner {
line-height:500px;
height:500px;
width:500px;
}
#img {
max-width: 100%;
max-height:100%;
display: block;
margin: 0 auto;
vertical-align: middle;
}
minimal partial example here: http://jsfiddle.net/cahs4/
I didn't do the vertical alignment but you can see what I mean
If you're consider to use jQuery, then you can have a look at the ImgCenter jQuery plugin here.
Is there a way (without binding to the window.resize event) to force a floating DIV to re-center itself when the browser window is resized?
To help explain, I imagine the pseudocode would look something like:
div.left = 50% - (div.width / 2)
div.top = 50% - (div.height / 2)
UPDATE
My query having been answered below, I wanted to post the final outcome of my quest - a jQuery extension method allowing you to center any block element - hope it helps someone else too.
jQuery.fn.center = function() {
var container = $(window);
var top = -this.height() / 2;
var left = -this.width() / 2;
return this.css('position', 'absolute').css({ 'margin-left': left + 'px', 'margin-top': top + 'px', 'left': '50%', 'top': '50%' });
}
Usage:
$('#mydiv').center();
This is easy to do with CSS if you have a fixed-size div:
.keepcentered {
position: absolute;
left: 50%; /* Start with top left in the center */
top: 50%;
width: 200px; /* The fixed width... */
height: 100px; /* ...and height */
margin-left: -100px; /* Shift over half the width */
margin-top: -50px; /* Shift up half the height */
border: 1px solid black; /* Just for demo */
}
The problem, of course, is that fixed-size elements aren't ideal.
The simplest way would be with the following CSS code:
#floating-div {
width: 50%;
border: 1px solid gray;
margin: 0 auto;
}
The key line of CSS code above is the "margin: 0 auto;" which tells the browser to automatically set the left/right margins to keep the div centered on the page, even when you resize the browser window.
Try this little article about Horizontal and Vertical centering. It is a little old and has a few hacks but you should be able to work out some test code from it.