【问题标题】:Centering a Div with a 100% width AND max width property?将具有 100% 宽度和最大宽度属性的 Div 居中?
【发布时间】:2013-06-01 21:19:02
【问题描述】:

关于如何使 div 居中的问题

当 div 有固定宽度(y px)时,我只使用 left: 50% 和 margin-left: -y/2 px;

但是,我如何将宽度为 100% 且最大宽度固定的 div 居中?即

body_container

{

position: absolute;
margin: auto;
max-width: 1750px;
height: 100%;
width: 100%;

}

【问题讨论】:

  • 如果你使用 100% 的宽度,如何让 div 居中?这将占据整个空间....对吗??只有当你有一个固定的宽度,你才能使它居中。
  • 我的理解是如果浏览器窗口大于1750px;宽度不再是 100%,而是 1750px;
  • 然后没问题。请尝试下面的代码

标签: html width center css


【解决方案1】:

试试这个 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>

【讨论】:

    猜你喜欢
    • 2012-03-24
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多