Whilst creating a website (queenalright.co.uk) I had issues with centering fixed divs in IE. This was made more difficult as I was trying to create a responsive layout and so the widths of various elements needed to be fluid. I solved this using a script called in the head to target versions of IE. Since then IE11 has been released and (in it's forward thinking) removed conditional comments but not added support for centering fixed or absolute div elements!
What would be the best approach to fix the problem or is there a whole easier way to go about this I don't know about?
here's the script:
// script to achieve horizontal centering in internet exporer! Grrrrr!
function topSize() {
// get screen width
var screenWidth = $(window).width();
// resize
var halfScreenWidth = screenWidth/2;
var topWidth = $('#top').width();
var topBGWidth = $('#top-bg').width();
var minusMarginInner = (-1)*(topWidth/2);
var minusMarginBG = (-1)*(topBGWidth/2);
$('#top').css({
"left":"50%",
"right":"auto", // overwrites the right 1% property previously used for centering
"margin-left":minusMarginInner + "px"
});
$('#top-bg').css({
"left":"50%",
"right":"0", // overwrites the right 1% property previously used for centering
"margin-left":minusMarginBG + "px"
});
}
$(document).ready(function() {
var screenWidth = $(window).width();
if (screenWidth >= 1096) {
topSize();
}
}); // document ready test window size and run topsize function
$(window).resize(function() {
var screenWidth = $(window).width();
if (screenWidth >= 1096) {
topSize();
}
}); // window resize test window size and run topsize function
If you find yourself asking how to target IE alone, you're probably better off taking a break and reconsidering the approach you're taking. Internet Explorer can center absolutely/fixed elements just as well as any other browser. In this particular case, the approach you took wasn't the most cross-browser compatible. Might I suggest an alternative.
.center {
position: fixed;
left: 50%;
transform: translateX(-50%);
}
This approach will work the same across all modern browsers, giving you a consistent experience. I've created a small demo fiddle demonstrating this: http://jsfiddle.net/Rx2Jb/show/.