Re-sizing the webpage content - javascript

In my project I have a webpage which has 2 div areas right and left. The left div takes almost 60% of the whole page width and the right one takes around 36% of the page. I wanted to resize the both div areas in a proper ratio when I shrink the browser from the right side or left side. The UI is getting generated from Javascript. This is the code.
boardHolderPadding = $board.outerHeight() - $board.height();
$board.height(viewportHeight - siblingsHeight - boardHolderPadding);
this.$('#board .droptarget').setWidthAsRatioOfHeight(this.options.ratio);
$('#sidebar').width($(window).width() - $board.find('#board').width() - 50);
I tried with JQuery resize plugin but couldnt get the proper result I'm looking for. Anyone have suggestion?
Thanks

See jsfiddle example but I think you just need to set your widths as percentages rather than trying to calculate them - note display is set to inline-block
<div>
<div class="small-left-column">this is the left column</div>
<div class="large-right-column">this is the right column</div>
</div>
<style>
.small-left-column {
width: 30%;
background-color: #aeaeae;
display: inline-block;
}
.large-right-column {
width: 60%;
background-color: #aeaeae;
display: inline-block;
}
</style>
So I think for your example your would have something like this
$(document).ready(function () {
$('#sidebar').addClass('small-left-column');
$('#board').addClass('large-right-column');
});

Maybe you're looking for the pure-Javascript version of the above:
$(document).ready(function () {
$('#sidebar').css( {
width: '30%'
backgroundColor: '#aeaeae',
display: 'inline-block'
});
$('#board').css({
width: '60%',
backgroundColor: '#aeaeae',
display: 'inline-block'
});
});

I did it in a different way in Javascript and I hope this will help someone to fix if they come across an issue like that
relativeSize : function(width, height){
var boardWidth = this.$("#board").width(),
boardHeight = this.$("#board").height(),
newcard = this.$("#newCard").width(),
space = width - boardWidth - newcard;
ratio = space / width * 3; //used to increment the ratio with 3 as the ratio is very tiny value, this will help to increase minimizing size
bheight = boardHeight - 25; // used to reduce the height by 25px, u can use any amount to match ur ratio
var relHeight = (space < ratio) ? bheight : height;
return relHeight;
}
Thanks

Related

Center DIV horizontal and vertical - jQuery or CSS [duplicate]

How do I go about setting a <div> in the center of the screen using jQuery?
I like adding functions to jQuery so this function would help:
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
Now we can just write:
$(element).center();
Demo: Fiddle (with added parameter)
I put a jquery plugin here
VERY SHORT VERSION
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
SHORT VERSION
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
Activated by this code :
$('#mainDiv').center();
PLUGIN VERSION
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
Activated by this code :
$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
is that right ?
UPDATE :
From CSS-Tricks
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* Yep! */
width: 48%;
height: 59%;
}
I would recommend jQueryUI Position utility
$('your-selector').position({
of: $(window)
});
which gives you much more possibilities than only centering ...
Here's my go at it. I ended up using it for my Lightbox clone. The main advantage of this solution is that the element will stay centered automatically even if the window is resized making it ideal for this sort of usage.
$.fn.center = function() {
this.css({
'position': 'fixed',
'left': '50%',
'top': '50%'
});
this.css({
'margin-left': -this.outerWidth() / 2 + 'px',
'margin-top': -this.outerHeight() / 2 + 'px'
});
return this;
}
You can use CSS alone to center like so:
Working Example
.center{
position: absolute;
height: 50px;
width: 50px;
background:red;
top:calc(50% - 50px/2); /* height divided by 2*/
left:calc(50% - 50px/2); /* width divided by 2*/
}
<div class="center"></div>
calc() allows you to do basic calculations in css.
MDN Documentation for calc()
Browser support table
I'm expanding upon the great answer given by #TonyL. I'm adding Math.abs() to wrap the values, and also I take into account that jQuery might be in "no conflict" mode, like for instance in WordPress.
I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.
The other thing I do is speed this up a bit by caching the $(window) object so that I reduce extra DOM traversals, and I use a cluster CSS.
jQuery.fn.center = function ($) {
var w = $(window);
this.css({
'position':'absolute',
'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
});
return this;
}
To use, you would do something like:
jQuery(document).ready(function($){
$('#myelem').center();
});
I would use the jQuery UI position function.
See working demo.
<div id="test" style="position:absolute;background-color:blue;color:white">
test div to center in window
</div>
If i have a div with id "test" to center then the following script would center the div in the window on document ready. (the default values for "my" and "at" in the position options are "center")
<script type="text/javascript">
$(function(){
$("#test").position({
of: $(window)
});
};
</script>
I would like to correct one issue.
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
Above code won't work in cases when this.height (lets assume that user resizes the screen and content is dynamic) and scrollTop() = 0, example:
window.height is 600
this.height is 650
600 - 650 = -50
-50 / 2 = -25
Now the box is centered -25 offscreen.
This is untested, but something like this should work.
var myElement = $('#myElement');
myElement.css({
position: 'absolute',
left: '50%',
'margin-left': 0 - (myElement.width() / 2)
});
I dont think having an absolute position would be best if you want an element always centered in the middle of the page. You probably want a fixed element. I found another jquery centering plugin that used fixed positioning. It is called fixed center.
Edit:
If the question taught me anything, it's this: don't change something that already works :)
I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:
.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper {#position:absolute; #top:50%;
display:table-cell; vertical-align:middle;}
.content {#position:relative; #top:-50%;
margin:0 auto; width:200px; border:1px solid orange;}
Fiddle: http://jsfiddle.net/S9upd/4/
I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.
Original:
Looks like I'm late to the party!
There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:
.container {
position:absolute;
left: 50%;
top: 50%;
overflow:visible;
}
.content {
position:relative;
margin:-50% 50% 50% -50%;
}
Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/
Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.
Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:
<table class="super-centered"><tr><td>
<div class="content">
<p>I am centered like a boss!</p>
</div>
</td></tr></table>
And than the content's position is fine-tuned with good old margin:0 auto;:
.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​
Working fiddle as promised: http://jsfiddle.net/teDQ2/
The transition component of this function worked really poorly for me in Chrome (didn't test elsewhere). I would resize the window a bunch and my element would sort of scoot around slowly, trying to catch up.
So the following function comments that part out. In addition, I added parameters for passing in optional x & y booleans, if you want to center vertically but not horizontally, for example:
// Center an element on the screen
(function($){
$.fn.extend({
center: function (x,y) {
// var options = $.extend({transition:300, minX:0, minY:0}, options);
return this.each(function() {
if (x == undefined) {
x = true;
}
if (y == undefined) {
y = true;
}
var $this = $(this);
var $window = $(window);
$this.css({
position: "absolute",
});
if (x) {
var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
$this.css('left',left)
}
if (!y == false) {
var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();
$this.css('top',top);
}
// $(this).animate({
// top: (top > options.minY ? top : options.minY)+'px',
// left: (left > options.minX ? left : options.minX)+'px'
// }, options.transition);
return $(this);
});
}
});
})(jQuery);
To center the element relative to the browser viewport (window), don't use position: absolute, the correct position value should be fixed (absolute means: "The element is positioned relative to its first positioned (not static) ancestor element").
This alternative version of the proposed center plugin uses "%" instead of "px" so when you resize the window the content is keep centered:
$.fn.center = function () {
var heightRatio = ($(window).height() != 0)
? this.outerHeight() / $(window).height() : 1;
var widthRatio = ($(window).width() != 0)
? this.outerWidth() / $(window).width() : 1;
this.css({
position: 'fixed',
margin: 0,
top: (50*(1-heightRatio)) + "%",
left: (50*(1-widthRatio)) + "%"
});
return this;
}
You need to put margin: 0 to exclude the content margins from the width/height (since we are using position fixed, having margins makes no sense).
According to the jQuery doc using .outerWidth(true) should include margins, but it didn't work as expected when I tried in Chrome.
The 50*(1-ratio) comes from:
Window Width: W = 100%
Element Width (in %): w = 100 * elementWidthInPixels/windowWidthInPixels
Them to calcule the centered left:
left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
= 50 * (1-elementWidthInPixels/windowWidthInPixels)
This is great. I added a callback function
center: function (options, callback) {
if (options.transition > 0) {
$(this).animate(props, options.transition, callback);
} else {
$(this).css(props);
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
}
What I have here is a "center" method that ensures the element you are attempting to center is not only of "fixed" or "absolute" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that.
$.fn.center = function () {
/// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>
var element = $(this),
elementPos = element.css('position'),
elementParent = $(element.parent()),
elementWidth = element.outerWidth(),
parentWidth = elementParent.width();
if (parentWidth <= elementWidth) {
elementParent = $(elementParent.parent());
parentWidth = elementParent.width();
}
if (elementPos === "absolute" || elementPos === "fixed") {
element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
}
};
CSS solution
In two lines only
It centralize your inner div horizontally and vertically.
#outer{
display: flex;
}
#inner{
margin: auto;
}
for only horizontal align, change
margin: 0 auto;
and for vertical, change
margin: auto 0;
i use this:
$(function() {
$('#divId').css({
'left' : '50%',
'top' : '50%',
'position' : 'absolute',
'margin-left' : -$('#divId').outerWidth()/2,
'margin-top' : -$('#divId').outerHeight()/2
});
});
Please use this:
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.
Here is my version. I may change it after I look at these examples.
$.fn.pixels = function(property){
return parseInt(this.css(property));
};
$.fn.center = function(){
var w = $($w);
return this.each(function(){
$(this).css("position","absolute");
$(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
$(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
});
};
No need jquery for this
I used this to center Div element.
Css Style,
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
Open element
$(document).ready(function(){
$(".open").click(function(e){
$(".black_overlay").fadeIn(200);
});
});
MY UPDATE TO TONY L'S ANSWER
This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position or only wanting horizontal/vertical centering rather than both.
center.js:
// We add a pos parameter so we can specify which position type we want
// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
this.css("position", pos);
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it vertically only
jQuery.fn.centerVer = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
return this;
}
In my <head>:
<script src="scripts/center.js"></script>
Examples of usage:
$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")
$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")
$("#example5").center("absolute")
$("#example6").center("fixed")
It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.
Hope this is useful for someone out there! Enjoy.
Lot's of ways to do this. My object is kept hidden with display:none just inside the BODY tag so that positioning is relative to the BODY. After using $("#object_id").show(), I call $("#object_id").center()
I use position:absolute because it is possible, especially on a small mobile device, that the modal window is larger than the device window, in which case some of the modal content could be inaccessible if positioning was fixed.
Here's my flavor based on other's answers and my specific needs:
$.fn.center = function () {
this.css("position","absolute");
//use % so that modal window will adjust with browser resizing
this.css("top","50%");
this.css("left","50%");
//use negative margin to center
this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");
//catch cases where object would be offscreen
if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});
return this;
};
You could use the CSS translate property:
position: absolute;
transform: translate(-50%, -50%);
Read this post for more details.
Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...
The following code centers a div both horizontally and vertically inside its container :
$("#target").addClass("centered-content")
.wrap("<div class='center-outer-container'></div>")
.wrap("<div class='center-inner-container'></div>");
body {
margin : 0;
background: #ccc;
}
.center-outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
}
.center-inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>
(see also this Fiddle)
Just say:
$("#divID").html($('').html($("#divID").html()));
It can be done with only CSS. But they asked with jQuery or JavaScript
Here, use CSS Flex box property to align the div center.
body.center{
display:flex;
align-items:center; // Vertical alignment
justify-content:center; // Horizontal alignment
}
align-items:center; - used to align vertically.
justify-content:center; - used to align horizontally.
document.querySelector("body").classList.add("center");
body {
margin : 0;
height:100vh;
width:100%;
background: #ccc;
}
#main{
background:#00cc00;
width:100px;
height:100px;
}
body.center{
display:flex;
align-items:center;
justify-content:center;
}
<body>
<div id="main"></div>
</body>
I used this to put the UL in the middle position.
cadasWidth = $('.card-dashboard').innerWidth();
cadasWidthCenter = cadasWidth/2;
ulmenuWidth = $('.card-dashboard ul#menu').outerWidth();
ulmenuWidthCenter = ulmenuWidth/2;
ulmenuStart = cadasWidthCenter - ulmenuWidthCenter;
$('.card-dashboard ul#menu').css({
'left' : ulmenuStart,
'position' : 'relative'
});
Why you don't use CSS for centering a div?
#timer_wrap{
position: fixed;
left: 50%;
top: 50%;
}

jQuery expand element from center not working

I am trying to make a zoom-like effect on hover event in a gallery exercise. What I need is for an image to seem to expand from its center, not down and right. If I understood correctly, I need to move it half way left and up for this to work. Also, I'm using em, so I try to convert em to pixels here.
Relevant html:
<div id="gallery">
<img src="img/cool1.gif">
<img src="img/cool2.gif" id="gal2">
<img src="img/cool3.gif" id="gal3">
</div>
CSS:
#gallery {
width: 31em;
margin-left: auto;
margin-right: auto;
}
#gallery img {
width: 10em;
height: auto;
position: absolute;
}
#gal2 {
margin-left: 10em;
}
#gal3 {
margin-left: 20em;
}
Finally, jQuery:
var fontSize = $("#gallery img").css("font-size");//equal to 1em?
var fontInt = parseInt(fontSize);
var t = $("#gallery img").position().top;
var tNew = t - (5 * fontInt);//top position
var l = $("#gallery img").position().left;
var lNew = l - (5 * fontInt);//left position
$("#gallery img").hover(
function() {
$(this).stop().css("zIndex", "1").animate({
height : "20em",
width : "20em",
top : tNew,
left : lNew
}, 400);
}, //end mouseover
function() {
$(this).stop().animate({
height : "10em",
width : "10em",
top : t,
left : l,
zIndex : "0"
}, 400);
} //end mouseout
);//end hover
edit 1 Images expand and change position, but not as expected. Also, they don't return on mouseout. Thanks to Racil Hilan for solving em-px conversion problem!
edit 2 Problem moslty solved by fixing variable scope – position values moved before hover() function. The only remaining bug is that the pictures escape to the top right corner of the body before returning to their place on first interaction. Afterwards, it runs as expected. Also, could somebody explain why this works when the fontInt variable is multiplied by five, not by 10?
edit 3 – solution As Mauricio Santamaria said below, just add the css() function setting top and left parameters before hover on #gallery img element like so:
$("#gallery img").css({"top" : t, "left" : l}).hover(...);
The rest stays the same.
I improvised a fiddle for this, too: http://jsfiddle.net/dzenesiz/wudw5hmu/15/
The problem is that the $(this).css("font-size"); returns the size with the unit (e.g. 16px) which is not a number and the calculation results in a NaN.
A quick solution is to parse it to an integer like this:
var fontSize = parseInt($(this).css("font-size")); //equal to 1em?
to remove the "jump" when first interaction you should set "top" and "left" on your css, this removes that behavior (tested on your fiddle with 8px or 0.4em equivalent to your initial image size), and for your question about why 5 gets your desired result its that the result of that operation (5 * fontInt) gives you the initial value of images ie. 100px (10em), and that's the amount for top and left that you need to make it zoom from center. (the initial value for fontSize is 20em, initial t =8, so 8-100 = -92, the right value taking in account the margin )

How to change div height if browser height is less than a given number of pixels?

I have a div that I want to be one of two sizes.
If browser window height is smaller than a given height, then it uses the smaller height for the div
However, if browser window height is larger than given height, then it uses larger height for the div
I tried the following code but it's not working. I need help to get it working.
Here is the jsbin: http://jsbin.com/oFIRawa/1
And here is the code I have so far:
page.html
<div id="theDiv"> </div>
style.css
#theDiv {
background: #000;
border: 2px solid #222;
width: 300px;
height: 400px;
margin: 50px auto 0 auto;
}
script.js
$(document).ready(function () {
// call the method one time
updateWindowSize();
// subscribe the method to future resize events
$(window).resize(updateWindowSize);
// variables
var updateWindowSize = (function(){
var minAllowedWindowHeight = 500;
var largerDivHeight = 400;
var smallerDivHeight = 300;
// actual updateWindowSize function
return function(){
var winHeight = $(window).height();
var newHeight = winHeight < minAllowedWindowHeight ? smallerDivHeight : largerDivHeight;
$('#theDiv').height(newHeight);
};
})();
});
You can do this in CSS my good sir. It's called responsive design!
#media (max-height:500px) {
Enter special css conditions for 500px height.
}
#media (max-height:200px) {
Enter special css conditions for 200px height.
}
This is more commonly used for max-width because it can tell us when someone is using a mobile device (something like 360px max-width), then we can modify our page to look nice on mobile. No fancy javascript needed!
var threshhold;
var smallerHeight = 50;
var largerHeight = 100;
if ($(window).height() < threshold)
$('#theDiv').height(smallerHeight);
else
$('#theDiv').height(largerHeight);
FIDDLE
Demo

How can i make my script center img in div

I have concocted a little script here out of bits and pieces I have found and scraped together, but I need a little help to add an extra function to it,
First of all - this is what it is doing for me at the moment:
It resizes and crops/letterboxes an image to completely fill a div
which is a % height and a % width – it keeps doing this whenever and
whatever window resize
It keeps working seamlessly as the window is resized
The image is filling 100% the area the div covers - left to right
and top to bottom.
The image is not being squashed or stretched - just being cropped
or is overflowing.
The image is kept as small as possible, so whatever the resize -
you can still see either the very sides OR the very top and bottom of
the image.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and Safari
over XP and 7
All of these things are very important to me, please don't tell me that all i need is:
<img style="width : 100%;">
This is so much more than that. It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Now, what I want to add:
All it is, I’d like the letter box to centre on the image.
When the div is a very tall portrait or a very flat landscape I’m just getting the top or just the left hand side of the image.
I’d like the centre of the original image to stay in the centre of the resized div.
I’ve tried a few things but have drawn a blank. I’m sure the script could feed a minus top: or left: into the style but it seems if I get too many div’s in div’s IE doesn’t like it, or what am I doing wrong?
Thing is I don’t really know how to wright this stuff, I only steal bit and bobs and splat them together…
And finally the demo
And the script:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
Thanks Very Much For This.
I'm not quiet sure if that's what you're looking for, but let's try this:
*upd: the wysiwyg is not working on comments at this moment, so sorry for messy code snippets.
1.Position the div#imgarea relatively. You can then float it to the right, to replicate your right:0px declaration. Don't forget to hide the overflow, to ensure that 'letter-boxed' parts of the image stay hidden.
#imgarea {
position: relative;
width: 70%;
height: 75%;
float: right;
overflow: hidden;
top: 25%;
};
Some user agents will add paddings and margins to the body element, thus preventing the image container to slide all the way to the right. Reset those, to get rid of the gaps between the container and the edge of the browser window.
body {
margin: 0;
padding: 0;
}
As for the image itself, position it absolutely.
img {
position: absolute;
}
And finally javascript. To center the image, you need to calculate what this width/height=auto sums up to, and then reset left/top attributes respectively. Your if function needs to be adjusted just a bit; leave your variables as is:
if (height_ratio > width_ratio) {
var newWidth, newHeight, newTop;
newWidth = area_width;
newHeight = image_height/width_ratio;
newTop = -(newHeight-area_height)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = newTop;
document.images[0].style.left = 0;
}else{
var newWidth, newHeight, newLeft;
newHeight = area_height;
newWidth = image_width/height_ratio;
newLeft = -(width-area_width)/2;
document.images[0].style.width = newWidth;
document.images[0].style.height = newHeight;
document.images[0].style.top = 0;
document.images[0].style.left = newLeft;
}
I hope that if this doesn't solve the issue completely, it at least sends you in the right direction. Good luck.
I'm not sure if this will work exactly, but may get your started. I had a client request a radial gradient be fixed to the left and right of a website's main ontent section. The page was set up with dynamic widths and I had a heck of a time getting one solid image to work, so I came up with a quick css solution.
#bgHold #gradLeft{
width:248px;
height:975px;
position:fixed;
right:50%;
margin-right:399px;
background:url("../images/gradLeft.png") top center no-repeat;
}
margin-right is half of the content block's width. So basically, the gradient is fixed on the page at 50% from the right, then shoved left 50% of the content box making it line up with the edge of the content. The same idea applies to the other side.
Now, with your situation, perhaps you can set right:50%; and margin-right:imgWidth/2?

Using jQuery to center a DIV on the screen

How do I go about setting a <div> in the center of the screen using jQuery?
I like adding functions to jQuery so this function would help:
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
Now we can just write:
$(element).center();
Demo: Fiddle (with added parameter)
I put a jquery plugin here
VERY SHORT VERSION
$('#myDiv').css({top:'50%',left:'50%',margin:'-'+($('#myDiv').height() / 2)+'px 0 0 -'+($('#myDiv').width() / 2)+'px'});
SHORT VERSION
(function($){
$.fn.extend({
center: function () {
return this.each(function() {
var top = ($(window).height() - $(this).outerHeight()) / 2;
var left = ($(window).width() - $(this).outerWidth()) / 2;
$(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
});
}
});
})(jQuery);
Activated by this code :
$('#mainDiv').center();
PLUGIN VERSION
(function($){
$.fn.extend({
center: function (options) {
var options = $.extend({ // Default values
inside:window, // element, center into window
transition: 0, // millisecond, transition time
minX:0, // pixel, minimum left element value
minY:0, // pixel, minimum top element value
withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
vertical:true, // booleen, center vertical
horizontal:true // booleen, center horizontal
}, options);
return this.each(function() {
var props = {position:'absolute'};
if (options.vertical) {
var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
top = (top > options.minY ? top : options.minY);
$.extend(props, {top: top+'px'});
}
if (options.horizontal) {
var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
left = (left > options.minX ? left : options.minX);
$.extend(props, {left: left+'px'});
}
if (options.transition > 0) $(this).animate(props, options.transition);
else $(this).css(props);
return $(this);
});
}
});
})(jQuery);
Activated by this code :
$(document).ready(function(){
$('#mainDiv').center();
$(window).bind('resize', function() {
$('#mainDiv').center({transition:300});
});
);
is that right ?
UPDATE :
From CSS-Tricks
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%); /* Yep! */
width: 48%;
height: 59%;
}
I would recommend jQueryUI Position utility
$('your-selector').position({
of: $(window)
});
which gives you much more possibilities than only centering ...
Here's my go at it. I ended up using it for my Lightbox clone. The main advantage of this solution is that the element will stay centered automatically even if the window is resized making it ideal for this sort of usage.
$.fn.center = function() {
this.css({
'position': 'fixed',
'left': '50%',
'top': '50%'
});
this.css({
'margin-left': -this.outerWidth() / 2 + 'px',
'margin-top': -this.outerHeight() / 2 + 'px'
});
return this;
}
You can use CSS alone to center like so:
Working Example
.center{
position: absolute;
height: 50px;
width: 50px;
background:red;
top:calc(50% - 50px/2); /* height divided by 2*/
left:calc(50% - 50px/2); /* width divided by 2*/
}
<div class="center"></div>
calc() allows you to do basic calculations in css.
MDN Documentation for calc()
Browser support table
I'm expanding upon the great answer given by #TonyL. I'm adding Math.abs() to wrap the values, and also I take into account that jQuery might be in "no conflict" mode, like for instance in WordPress.
I recommend that you wrap the top and left values with Math.abs() as I have done below. If the window is too small, and your modal dialog has a close box at the top, this will prevent the problem of not seeing the close box. Tony's function would have had potentially negative values. A good example on how you end up with negative values is if you have a large centered dialog but the end user has installed several toolbars and/or increased his default font -- in such a case, the close box on a modal dialog (if at the top) might not be visible and clickable.
The other thing I do is speed this up a bit by caching the $(window) object so that I reduce extra DOM traversals, and I use a cluster CSS.
jQuery.fn.center = function ($) {
var w = $(window);
this.css({
'position':'absolute',
'top':Math.abs(((w.height() - this.outerHeight()) / 2) + w.scrollTop()),
'left':Math.abs(((w.width() - this.outerWidth()) / 2) + w.scrollLeft())
});
return this;
}
To use, you would do something like:
jQuery(document).ready(function($){
$('#myelem').center();
});
I would use the jQuery UI position function.
See working demo.
<div id="test" style="position:absolute;background-color:blue;color:white">
test div to center in window
</div>
If i have a div with id "test" to center then the following script would center the div in the window on document ready. (the default values for "my" and "at" in the position options are "center")
<script type="text/javascript">
$(function(){
$("#test").position({
of: $(window)
});
};
</script>
I would like to correct one issue.
this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
Above code won't work in cases when this.height (lets assume that user resizes the screen and content is dynamic) and scrollTop() = 0, example:
window.height is 600
this.height is 650
600 - 650 = -50
-50 / 2 = -25
Now the box is centered -25 offscreen.
This is untested, but something like this should work.
var myElement = $('#myElement');
myElement.css({
position: 'absolute',
left: '50%',
'margin-left': 0 - (myElement.width() / 2)
});
I dont think having an absolute position would be best if you want an element always centered in the middle of the page. You probably want a fixed element. I found another jquery centering plugin that used fixed positioning. It is called fixed center.
Edit:
If the question taught me anything, it's this: don't change something that already works :)
I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:
.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper {#position:absolute; #top:50%;
display:table-cell; vertical-align:middle;}
.content {#position:relative; #top:-50%;
margin:0 auto; width:200px; border:1px solid orange;}
Fiddle: http://jsfiddle.net/S9upd/4/
I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.
Original:
Looks like I'm late to the party!
There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:
.container {
position:absolute;
left: 50%;
top: 50%;
overflow:visible;
}
.content {
position:relative;
margin:-50% 50% 50% -50%;
}
Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/
Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.
Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:
<table class="super-centered"><tr><td>
<div class="content">
<p>I am centered like a boss!</p>
</div>
</td></tr></table>
And than the content's position is fine-tuned with good old margin:0 auto;:
.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}​
Working fiddle as promised: http://jsfiddle.net/teDQ2/
The transition component of this function worked really poorly for me in Chrome (didn't test elsewhere). I would resize the window a bunch and my element would sort of scoot around slowly, trying to catch up.
So the following function comments that part out. In addition, I added parameters for passing in optional x & y booleans, if you want to center vertically but not horizontally, for example:
// Center an element on the screen
(function($){
$.fn.extend({
center: function (x,y) {
// var options = $.extend({transition:300, minX:0, minY:0}, options);
return this.each(function() {
if (x == undefined) {
x = true;
}
if (y == undefined) {
y = true;
}
var $this = $(this);
var $window = $(window);
$this.css({
position: "absolute",
});
if (x) {
var left = ($window.width() - $this.outerWidth())/2+$window.scrollLeft();
$this.css('left',left)
}
if (!y == false) {
var top = ($window.height() - $this.outerHeight())/2+$window.scrollTop();
$this.css('top',top);
}
// $(this).animate({
// top: (top > options.minY ? top : options.minY)+'px',
// left: (left > options.minX ? left : options.minX)+'px'
// }, options.transition);
return $(this);
});
}
});
})(jQuery);
To center the element relative to the browser viewport (window), don't use position: absolute, the correct position value should be fixed (absolute means: "The element is positioned relative to its first positioned (not static) ancestor element").
This alternative version of the proposed center plugin uses "%" instead of "px" so when you resize the window the content is keep centered:
$.fn.center = function () {
var heightRatio = ($(window).height() != 0)
? this.outerHeight() / $(window).height() : 1;
var widthRatio = ($(window).width() != 0)
? this.outerWidth() / $(window).width() : 1;
this.css({
position: 'fixed',
margin: 0,
top: (50*(1-heightRatio)) + "%",
left: (50*(1-widthRatio)) + "%"
});
return this;
}
You need to put margin: 0 to exclude the content margins from the width/height (since we are using position fixed, having margins makes no sense).
According to the jQuery doc using .outerWidth(true) should include margins, but it didn't work as expected when I tried in Chrome.
The 50*(1-ratio) comes from:
Window Width: W = 100%
Element Width (in %): w = 100 * elementWidthInPixels/windowWidthInPixels
Them to calcule the centered left:
left = W/2 - w/2 = 50 - 50 * elementWidthInPixels/windowWidthInPixels =
= 50 * (1-elementWidthInPixels/windowWidthInPixels)
This is great. I added a callback function
center: function (options, callback) {
if (options.transition > 0) {
$(this).animate(props, options.transition, callback);
} else {
$(this).css(props);
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(this); // brings the scope to the callback
}
}
What I have here is a "center" method that ensures the element you are attempting to center is not only of "fixed" or "absolute" positioning, but it also ensures that the element you are centering is smaller than its parent, this centers and element relative to is parent, if the elements parent is smaller than the element itself, it will pillage up the DOM to the next parent, and center it relative to that.
$.fn.center = function () {
/// <summary>Centers a Fixed or Absolute positioned element relative to its parent</summary>
var element = $(this),
elementPos = element.css('position'),
elementParent = $(element.parent()),
elementWidth = element.outerWidth(),
parentWidth = elementParent.width();
if (parentWidth <= elementWidth) {
elementParent = $(elementParent.parent());
parentWidth = elementParent.width();
}
if (elementPos === "absolute" || elementPos === "fixed") {
element.css('right', (parentWidth / 2) - elementWidth / 2 + 'px');
}
};
CSS solution
In two lines only
It centralize your inner div horizontally and vertically.
#outer{
display: flex;
}
#inner{
margin: auto;
}
for only horizontal align, change
margin: 0 auto;
and for vertical, change
margin: auto 0;
i use this:
$(function() {
$('#divId').css({
'left' : '50%',
'top' : '50%',
'position' : 'absolute',
'margin-left' : -$('#divId').outerWidth()/2,
'margin-top' : -$('#divId').outerHeight()/2
});
});
Please use this:
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
you're getting that poor transition because you're adjusting the position of the element every time the document is scrolled. What you want is to use fixed positioning. I tried that fixed center plugin listed above and that seems to do solve the problem nicely. Fixed positioning allows you to center an element once, and the CSS property will take care of maintaining that position for you every time you scroll.
Here is my version. I may change it after I look at these examples.
$.fn.pixels = function(property){
return parseInt(this.css(property));
};
$.fn.center = function(){
var w = $($w);
return this.each(function(){
$(this).css("position","absolute");
$(this).css("top",((w.height() - $(this).height()) / 2) - (($(this).pixels('padding-top') + $(this).pixels('padding-bottom')) / 2) + w.scrollTop() + "px");
$(this).css("left",((w.width() - $(this).width()) / 2) - (($(this).pixels('padding-left') + $(this).pixels('padding-right')) / 2) + w.scrollLeft() + "px");
});
};
No need jquery for this
I used this to center Div element.
Css Style,
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
Open element
$(document).ready(function(){
$(".open").click(function(e){
$(".black_overlay").fadeIn(200);
});
});
MY UPDATE TO TONY L'S ANSWER
This is the modded version of his answer that I use religiously now. I thought I would share it, as it adds slightly more functionality to it for various situations you may have, such as different types of position or only wanting horizontal/vertical centering rather than both.
center.js:
// We add a pos parameter so we can specify which position type we want
// Center it both horizontally and vertically (dead center)
jQuery.fn.center = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it horizontally only
jQuery.fn.centerHor = function (pos) {
this.css("position", pos);
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
// Center it vertically only
jQuery.fn.centerVer = function (pos) {
this.css("position", pos);
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
return this;
}
In my <head>:
<script src="scripts/center.js"></script>
Examples of usage:
$("#example1").centerHor("absolute")
$("#example2").centerHor("fixed")
$("#example3").centerVer("absolute")
$("#example4").centerVer("fixed")
$("#example5").center("absolute")
$("#example6").center("fixed")
It works with any positioning type, and can be used throughout your entire site easily, as well as easily portable to any other site you create. No more annoying workarounds for centering something properly.
Hope this is useful for someone out there! Enjoy.
Lot's of ways to do this. My object is kept hidden with display:none just inside the BODY tag so that positioning is relative to the BODY. After using $("#object_id").show(), I call $("#object_id").center()
I use position:absolute because it is possible, especially on a small mobile device, that the modal window is larger than the device window, in which case some of the modal content could be inaccessible if positioning was fixed.
Here's my flavor based on other's answers and my specific needs:
$.fn.center = function () {
this.css("position","absolute");
//use % so that modal window will adjust with browser resizing
this.css("top","50%");
this.css("left","50%");
//use negative margin to center
this.css("margin-left",(-1*this.outerWidth()/2)+($(window).scrollLeft())+"px");
this.css("margin-top",(-1*this.outerHeight()/2)+($(window).scrollTop())+"px");
//catch cases where object would be offscreen
if(this.offset().top<0)this.css({"top":"5px","margin-top":"0"});
if(this.offset().left<0)this.css({"left":"5px","margin-left":"0"});
return this;
};
You could use the CSS translate property:
position: absolute;
transform: translate(-50%, -50%);
Read this post for more details.
Normally, I would do this with CSS only... but since you asked you a way to do this with jQuery...
The following code centers a div both horizontally and vertically inside its container :
$("#target").addClass("centered-content")
.wrap("<div class='center-outer-container'></div>")
.wrap("<div class='center-inner-container'></div>");
body {
margin : 0;
background: #ccc;
}
.center-outer-container {
position : absolute;
display: table;
width: 100%;
height: 100%;
}
.center-inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<div id="target">Center this!</div>
(see also this Fiddle)
Just say:
$("#divID").html($('').html($("#divID").html()));
It can be done with only CSS. But they asked with jQuery or JavaScript
Here, use CSS Flex box property to align the div center.
body.center{
display:flex;
align-items:center; // Vertical alignment
justify-content:center; // Horizontal alignment
}
align-items:center; - used to align vertically.
justify-content:center; - used to align horizontally.
document.querySelector("body").classList.add("center");
body {
margin : 0;
height:100vh;
width:100%;
background: #ccc;
}
#main{
background:#00cc00;
width:100px;
height:100px;
}
body.center{
display:flex;
align-items:center;
justify-content:center;
}
<body>
<div id="main"></div>
</body>
I used this to put the UL in the middle position.
cadasWidth = $('.card-dashboard').innerWidth();
cadasWidthCenter = cadasWidth/2;
ulmenuWidth = $('.card-dashboard ul#menu').outerWidth();
ulmenuWidthCenter = ulmenuWidth/2;
ulmenuStart = cadasWidthCenter - ulmenuWidthCenter;
$('.card-dashboard ul#menu').css({
'left' : ulmenuStart,
'position' : 'relative'
});
Why you don't use CSS for centering a div?
#timer_wrap{
position: fixed;
left: 50%;
top: 50%;
}

Categories

Resources