html - 将具有 100% 宽度和最大宽度属性的 Div 居中?

标签 html width center css

一个关于如何让div居中的问题

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

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

主体容器

{

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>

关于html - 将具有 100% 宽度和最大宽度属性的 Div 居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873049/

相关文章:

javascript - 如何在图像之间留出空间?

jquery - $(element).outerWidth(true) 根据主题报告不同?

html - 居中多个DIV :s

css - DIV 底部的中心图像

javascript - 为什么我无法使用 jquery 设置 div 的 z-index?

html - 为什么 rowspan html 不能按预期工作?

javascript - 如何更改ionic 3中的后退按钮

css - 调整 Wordpress 小部件的宽度百分比

html - 如何使 HTML 表格(在固定宽度的 div 中)适应其单元格而不是容器的宽度?

html - 标题以桌面为中心,而不是移动?