resizing and centering an <img> inside a div and keeping aspect ratio - javascript

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.

Related

centering a div in a container larger than 100%

i need to center a div in the viewport in a container larger then 100%.
assuming it's 160% large, i prepared this fiddle:
https://jsfiddle.net/mz0bbz14/2/
usually i would go for:
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
but this works only when its container is 100% large.
it's solved with this css
position:absolute;
top:50%;
text-align: center;
transform:translate(0,-50%);
width: 100vw;
but the vw unit doesn't work on older android browsers and i need to support it. I can't use jQuery and i don't know how to center it with pure javascript.
i tried setting .div to half the width of the container, but the text inside the div doesn't visually center.
i can't find a solution. any ideas? thanks
If I understand your problem correctly, you want the red .div centered in the left 100% of the parent container that has a width of 160% of the view port.
In that case, you need to adjust the left offset to be 50% of 100%/160%, which is 31.25%.
body,html {
height: 100%;
}
.cont-inner {
width:160%;
height: 100%;
background: hotpink;
position:relative;
}
.div {
position:absolute;
top:50%;
left: 31.25%;
transform:translate(-50%,-50%);
background:red;
padding:50px; /* smaller size for demo in snippet window */
}
<div class="cont-inner">
<div class="div">
asd
</div>
</div>
You need to change the left property.
It needs to be in the middle of the visible part of the container.
Since it's 160%, it is
(100 / 160) * 0.5 -> 31.25%
body,html {
height: 100%;
}
.cont-inner {
width:160%;
height: 100%;
background: hotpink;
position:relative;
}
.div {
position:absolute;
top:50%;
left:31.25%;
transform:translate(-50%,-50%);
background:red;
padding:100px;
}
<div class="cont-inner">
<div class="div">
asd
</div>
</div>
;
I wanted to place an answer with modified left property, but I already see them, so here's some other attempt with position:static freeing inner div from its parent
https://jsfiddle.net/mz0bbz14/9/
It just doesn't force you to stick with 160%.
If you need to support older browsers you shall use Javascript to make sure it will work since all CSS solution require hard-coding values.
var parent = document.querySelector('.cont-inner'),
child = parent.querySelector('div');
child.style.left = ((window.innerWidth / 2) - (child.offsetWidth / 2)) + 'px';
child.style.top = ((window.innerHeight / 2) - (child.offsetHeight / 2)) + 'px';
Example: https://jsfiddle.net/9syvq2r2/

Using JavaScript to center multiple divs in a fluid layout

I'm trying to align multiple divs in the center of a container div. I am using the modulus function to work out the padding needed from the left hand side of the page. Here is the JavaScript I am using:
JavaScript
window.addEventListener("resize", winResize, false);
var width, leftPad, space, boxWidth;
winResize();
function winResize() {
width = document.getElementById('body').offsetWidth;
boxWidth = 350 + 10 + 10;
space = width % boxWidth;
document.getElementById('a').innerHTML = width + '....' + space;
leftPad = space / 2;
document.getElementById('container').style.paddingLeft = leftPad + 'px';
document.getElementById('container').style.width -= leftPad;
};
The HTML is as follows:
<div id="container">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</div>
And the CSS:
#container {
width: 100%;
float: left;
}
#container .block {
width: 350px;
height: 350px;
background-color: 4e4e4e;
float: left;
margin: 10px;
}
My problem is with this code, the padding on the left pushes the container div to the right, which makes the page wider than the window. I have tried removing the padding from the width of the container (in the bottom line of the winResize function) but this doesn't seem to do anything. Is there a way I can remove this "excess div" with CSS padding/margins?
What I can perceive is that you are trying to make container look in the center of your page, js is not required to do it and prefer not use js to position static elements in your page ever.
Here is the css you should use to make it come in center and fluidic
#container {
width: 100%;
text-align:center;
}
#container .block {
width: 350px;
height: 350px;
background-color: #4e4e4e;
display:inline-block;
margin: 10px;
}
Also you can see this fiddle : http://jsfiddle.net/ghFRv/
I would like to know if there is any reason why you want to CENTER an html element?
This is a CSS job and CSS does a very good job at it.
If you want to center your DIVS you could use margin: 0 auto; on the .block.
This would center your layout and keep the elements block level as well.
Your css would look like this:
#container {
width: 100%; /*Remove the float, it's not needed. Elements align top-left standard.*/
}
#container div.block {
width: 350px; /*Makes it possible for margin to center the box*/
height: 350px;
background: #4e4e4e; /*background is the shorthand version*/
margin: 10px auto; /*10px to keep your margin, auto to center it.*/
}
This should get rid of your problem, and makes your page load faster since theres no JS plus, the layout can never be "disabled" due to JS being disabled.
Hope this helped, if it did don't forget to upvote / accept answer
&dash; Sid

CSS: Keeping a div's height relative to its width [duplicate]

This question already has answers here:
Maintain the aspect ratio of a div with CSS
(37 answers)
Closed 7 years ago.
My question is very similar to this question: CSS: 100% width or height while keeping aspect ratio?
I have a div whose position is fixed. The width of the div must be 100% and its height exactly 1/6th of its width. Is there a -webkit-calc() way of doing this?
Note: JS solutions are not preferred as a zoom/orientation change can affect the width/height.
Is this what you are after? I'm not using -webkit-calc() at all. I've inserted a 1px by 6px image into a outer div which has position: fixed applied to it, and set the image to have a width of 100% and position: relative. Then I have added an inner div which is absolutely positioned to be as high and wide as its ancestor.
Now you can change the width of the outer div, and the images' width: 100% setting will ensure that both the outer and the inner div's are guaranteed to always have a height equal to 1/6th of their width (or at least as close to exactly equal as it can get, the heights will be rounded off to the closest whole number of pixels). Any content could go inside the inner div.
HTML
<div>
<div></div>
<img src="https://dl.dropboxusercontent.com/u/6928212/sixbyone.png" />
</div>
CSS
html, body {
margin: 0px;
padding: 0px;
}
div {
position: fixed;
width: 100%;
}
div > div {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
img {
width: 100%;
display: block;
position: relative;
}
Here's a jsFiddle showing the requested behaviour.
You can also use the solution I described in Responsive square columns.
It is based on the fact that % padding-top/bottom and margin-top/bottom are calculated according to the whidth of the parent element.
Adapted to your situation it would look like this :
FIDDLE
HTML :
<div class="wrap">
<div class="content">
</div>
</div>
CSS :
.wrap{
position:fixed;
width:100%;
padding-bottom:16.666%; /* 100x1/6 = 16.666...*/
}
.content{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
}
you can always set div width like this:
$('#div1').css("width", $('#div1').height()/6);
EDIT:
or you could use something like this:
/* Firefox */
width: -moz-calc(100% / 6);
/* WebKit */
width: -webkit-calc(100% / 6);
/* Opera */
width: -o-calc(100% / 6);
/* Standard */
width: calc(100% / 6);
This is only an example-..But it is impossible to get height of a div in a pixels in the css file..you need to use jquery for that
EDIT:
height 1/6 of a width
$('#div1').css("height", window.width()/6);
you could use jquery, e.g.$('.someclass').css('width', 180);
$('.someclass').css('height', $('.someclass').width() / 6);
moved the second suggestion from the comment for readability
$('.btnResize').click(function() { $('.div').css('height', $('.div').width()/6);});

Absolute position after zooming

I have divs with class="myDiv". I need to do this logic: on mouse over, I want to show a popup in the middle of the div.
For that I have the following:
$(".myDiv").mouseover(function () {
positionDiv($(this).position().left + $(this).width() / 2, $(this).position().top + $(this).height() / 2);
});
function positionDiv(xPosition ,yPosition ) {
$("#popupWindow").css("left", xPosition + "px");
$("#popupWindow").css("top", yPosition + "px");
$("#popupWindow").show();
}
The CSS:
.popupWindow{
position:absolute;
width:313px;
height:383px;
display:none;
}
This will position the popup window in the middle of the div on mouse over. Everything works great at this point.
However, if the website is zoomed in (using the browser zoom functionality), tHe position will get messed up. The popup window no longer appears in the middle of myDiv.
Any idea what might be the problem?
Edit:
For more info, if it is created and I zoom it, it is fine. But when I move my mouse to another myDiv and the new popup appears in a weird position. The left and top attribute of the Div are messing up.
You don't need JS for this:
http://jsfiddle.net/coma/6VUpS/1/
The key is to play with CSS and avoid JS calculations. The container div (myDiv) should be position: relative, the popup must be inside and position: absolute, top and left to 50% and using negative margins to center it (http://www.css-101.org/negative-margin/06.php).
Try avoiding JS for visual fanciness, only CSS ensures the correct position even on zoom since it's rendered by the browser.
HTML
<div class="myDiv">
Hi!
<div class="popupWindow">you are welcome!</div>
</div>
CSS
div.myDiv {
padding: 10px;
background-color: #eee;
margin: 50px 0;
position: relative;
}
div.popupWindow {
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -100px;
width: 200px;
line-height: 100px;
background-color: #111;
color: #fff;
text-align: center;
display: none;
pointer-events: none;
}
div.myDiv:hover > div.popupWindow {
display: block;
}
Bonus track using a checkbox to click/tap/toggle popup and some fade in:
http://jsfiddle.net/coma/6VUpS/3/
More hacky:
http://jsfiddle.net/coma/6VUpS/
More complex example:
http://jsfiddle.net/coma/dHTHG/
I understand your problem and my solution is to put every object containing a pop up in pos relative and then set your pop up with those CSS :
.myPopUp{
position:absolute;
display : none;
width:400px;
height : 100px;
margin-top : -50px;
margin-left:-200px;
background-color: red;
top : 50%;
left: 50%;
}
It will alway be centered.
Now i understand you have only 1 pop up for all your hoverable div. My trick is to save the pop up in a var and remove it from its parent container to append it in the hovered div like this :
var popUp = $('.myPopUp');
$('.myDiv').mouseover(appendPopUp);
$('.myDiv').mouseout(function(){popUp.css('display', 'none')});
function appendPopUp(){
console.log(popUp.parent(), $(this))
if(popUp.parent()[0] != $(this)[0]){
popUp.remove();
$(this).append(popUp);
}
popUp.css('display', 'block')
}
That should work, here's my fiddle : http://jsfiddle.net/7EEZT/
$(window).on('resize', function(){
var $md = $('.myDiv');
positionDiv($md.position().left + $md.width() / 2, $md.position().top + $(this).height() / 2);
});
I have a simple css solution if you have a div with known height and width you can do same task with help of css only
.popupWindow {
position:absolute;
width:313px;
height:383px;
left:50%;
top:50%;
margin-left:-156px;/*half of width*/
margin-top:-191px;/*half of height*/
display:none;
}
Go with position:relative and try this. It will solved your problem relate to position.
$(".myDiv").mouseover(function () {
positionDiv( $(this).width() / 2, $(this).height() / 2);
});
function positionDiv(xPosition ,yPosition ) {
$("#popupWindow").css("left","-" + xPosition + "px");
$("#popupWindow").css("top", "-" + yPosition + "px");
$("#popupWindow").show();
}
The CSS:
.popupWindow{
position:relative;
width:313px;
height:383px;
display:none;
}
http://jsfiddle.net/kishan6446/PdNkg/13/

How can I display a regular image as a rounded one?

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.

Categories