divを中央に配置する方法に関する質問
div が固定幅 (y px) の場合、左: 50% とマージン左: -y/2 px; を使用します。
しかし、幅:100% で最大幅が固定されている div を中央に配置するにはどうすればよいでしょうか? すなわち
body_container
{
position: absolute;
margin: auto;
max-width: 1750px;
height: 100%;
width: 100%;
}
この jQuery を試して、ページの中心に div を作成します。
<script>
jQuery.fn.vh_center = function (absolute) {
return this.each(function () {
var t = jQuery(this);
t.css({
position: absolute ? 'absolute' : 'fixed',
left: '50%',
top: '50%',
}).css({
marginLeft: '-' + (t.outerWidth() / 2) + 'px',
marginTop: '-' + (t.outerHeight() / 2) + 'px'
});
if (absolute) {
t.css({
marginTop: parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(),
marginLeft: parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
});
}
});
};
$(document).ready(function(){
$('#Your_div').vh_center();
});
</script>