Reputation: 385
i've a problem with my jQuery: i'm using a script that allows me to center elements by giving them a class, but this script doesn't take the correct height.
This is my HTML code:
<div class="logoutscreen blackbackground">
<div class="window centered" style="display: block;">
[CONTENT HERE]
</div>
</div>
And this my jQuery code:
$(function () {
$(".centered").css({
'position': 'absolute',
'left': '50%',
'top': '50%',
'margin-left': -$(this).outerWidth() / 2,
'margin-top': -$(this).outerHeight() / 2
});
});
The problem is that the script doesn't take Height and Width of the div with .centered class (.window), but of his parent (.logoutscreen).
Why this happens? :(
Upvotes: 0
Views: 110
Reputation: 16359
The use of $(this)
is your problem here. Unlike other methods, you cannot access the this
parent object as $('.centered')
in jQuery's .css()
method ... it will default to the global window
object.
What you want to do is cache your object and reference it explicitly:
var $centered = $('.centered');
$centered.css({
position:'absolute',
left:'50%',
top:'50%',
marginLeft:((-1 * $centered.outerWidth()) / 2),
marginTop:((-1 * $centered.outerHeight()) / 2)
});
This should give you what you're looking for. If you have multiple instances, however, you'll need to do something like this:
$centered.each(function(){
var $self = $(this);
$self.css({
position:'absolute',
left:'50%',
top:'50%',
marginLeft:((-1 * $self.outerWidth()) / 2),
marginTop:((-1 * $self.outerHeight()) / 2)
});
});
That way each unique height
and width
is respected.
Upvotes: 1
Reputation: 25682
this
is not $('.centered')
.
Use:
$(function () {
var centered = $('.centered').first();
centered.css({
'position': 'absolute',
'left': '50%',
'top': '50%',
'margin-left': -centered.outerWidth() / 2,
'margin-top': -centered.outerHeight() / 2
});
});
Upvotes: 0