Reputation: 139
I'm about to enter jQuery world in a more specific way, so i've written a function to center absolute positioned anchor elements within relative positioned divs, by setting css left property according to the child & parents outerWidth.
Here it is:
$.fn.moreCenter = function() {
var sblockWidth = $(this).outerWidth();
var moreWidth = $(this).children('a').outerWidth();
var moreLeft = (sblockWidth - moreWidth)/2;
$(this).children('a').css('left', moreLeft + 'px');
};
then I target the parent div by their class:
$(document).ready(function() {
$('.single-block').moreCenter();
});
The point is that .single-block structure is repeated in many parts of the page, and each .single-block may be of different widths. This is the reason why the function generalizes the parent div using (this).
However, the function seems to apply the same left value to each ".single-block a" element, calculated on the basis of the first .single-block it finds, without re-calculating it for each element.
What's wrong with the code?
Upvotes: 1
Views: 104
Reputation: 139
SonnyPrince transform/translate won't work in older browsers.
Thanks to Paulie_D, I was able to center the child anchor elements via css in this way.
parent { position: relative;
width: can be expressed in %;
whateverprop: whoteverset; }
child { position: absolute;
left: 0;
right: 0;
margin: 0 auto; }
Anyway, I managed even to correct the jQuery function above by using .each().
$.fn.moreCenter = function() {
$(this).each(function() {
var sblockWidth = $(this).outerWidth();
var moreWidth = $(this).children('a').outerWidth();
var moreLeft = (sblockWidth - moreWidth)/2;
$(this).children('a').css('left', moreLeft + 'px');
});
};
Question solved to me, thanks guys :)
Upvotes: 1
Reputation: 1152
a very simple solution just using CSS would be:
.single-block {
left: 50%;
position: absolute;
transform: translateX(-50%);
}
Upvotes: 0