jQuery Center Div toggle in IE6
Click the button to center div, click again to left align. This works in all browsers except IE6. IE6 doesn't support margin:0 auto;
How can i work around this. div width is dynamic and not always 200px.
Check jsfiddle http://jsfiddle.net/hZ23J/1/
<button id="center">Left Align</button>
<div></div>
$('#center').toggle(function() {
$('div').css('margin', '0');
$(this).text('Center Align')
}, function() {
$('div').css('margin', '0 auto');
开发者_高级运维$(this).text('Left Align')
});
For IE6 use
body{
text-align:center;
}
And your jQuery code will look like
$('#center').toggle(function() {
$('div').css('margin', '0');
$('body').css('text-align', 'left');
$(this).text('Center Align')
}, function() {
$('div').css('margin', '0 auto');
$('body').css('text-align', 'center');
$(this).text('Left Align')
});
Check working example at http://jsfiddle.net/jNWYP/1/
This solution works for me in IE6...
$('#center').click(function () {
$('div').toggleClass('center');
});
class...
.center { margin: 0px auto; }
It's also good practice to keep your JS and CSS separate when possible.
Here is my doctype...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
精彩评论