Reputation: 1078
Googled around and found a jQuery script for auto centering a div, horizontally and vertically.
Added exact the same as the example gives but by one reason the div is not centered by page load, only on window resize.
Example link code: http://demo.tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/demo.html
Example demo: http://demo.tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/3.html
The link I made is online (test): http://i333180.iris.fhict.nl/test/index.html
And as you can notice by source-center.js, it is just the same as the examples code is given but it only centers when window is resized.. Thanks
Upvotes: 1
Views: 850
Reputation: 13620
In your example, you are taking the width of a block-level element - by definition it takes up the full width of its parent. So, the item is already centered, but your text is left aligned inside it. You need to declare your div
as an inline-block
element, then the horizontal centering will work.
A good explanation can be found here: https://stackoverflow.com/a/9189873/844726
Here is the code - I only added the style
attribute to your div
(purely for example):
The HTML:
<div class="className" style="display: inline-block">
<p>Centered In The Middle Of The Page With jQuery</p>
</div>
And the JS:
$(document).ready(function(){
$(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();
});
Upvotes: 1
Reputation: 121
As an alternative to the inline-block answer you can use position:absolute just add
.className{
position:absolute;
}
to your css file.
https://jsfiddle.net/26y9aue4/2/
Upvotes: 0
Reputation:
Auto centering a div in a div is quit easy, Here is a code you cloud try!
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Demo: https://css-tricks.com/centering-css-complete-guide/
Upvotes: 0