【问题标题】:How can I center multiple divs on a page, and left-align them when a div drops to next row?如何在一个页面上居中多个 div,并在 div 下降到下一行时将它们左对齐?
【发布时间】:2012-01-09 23:45:12
【问题描述】:

我有一个包含多个“模块”的页面,这些“模块”由单独的 <div>s 组成,宽 159 像素,高 160 像素。模块应该形成一个居中的行。包含的<div> 设置为 70% 宽度。

当调整窗口大小以使一个或多个模块下降到下一行时,我希望它们左对齐而不是居中下一行,这样您就不会看到(例如)四个模块一个在上面,一个在它们下面。

这意味着使用text-align: center 不是一种选择,这是不幸的,因为否则它们会完全居中。使用我当前的 CSS,它们有点居中,但是当一个模块下降到下一行时,居中 <div> 不会调整回内容宽度,因此它不是完全居中的。这是可以用CSS解决的吗?如果没有,我愿意使用 jQuery。

#modulesAreaBlock { /*Outer containing DIV*/
    margin-top: 50px;
    width:70%;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}

#modulesCenter { /*DIV for centering the modules inside the outer DIV*/
    display: inline-block;
    text-align: left;
}

.moduleBlock { /*The individual "module" DIVs*/
    text-align:center;
    height: 160px;
    width: 159px;
    margin-bottom: 2px;
    display: inline-block;
    zoom: 1;
    *display: inline;
    _height: 160px;
}

【问题讨论】:

  • 我通过将 modulesCenter DIV 更改为跨度使其在 IE8 中工作,但在 Chrome、Firefox 和 IE9 中它仍然无法正确居中。
  • 我刚刚在这里回答了一个类似的问题stackoverflow.com/questions/8331150/…
  • 多么巧合!这几乎正​​是我想要做的,只是我没有使用列表。我会看看我是否可以调整它以适应我的代码。
  • 好的,我设置了一个页面,其中包含我的网站设置示例:jsfiddle.net/9Qgsm
  • @Scott 用更多颜色更新了链接,以显示当所有模块 div 位于同一行时,居中 div 才居中:jsfiddle.net/9Qgsm/1

标签: jquery css html centering


【解决方案1】:

您是否尝试过将模块向左浮动并将其显示设置为块而不是使用内联块。 Inline-block 对跨浏览器不太友好,尤其是在 IE 中。

【讨论】:

  • 是的,同样的问题......一旦有东西掉到下一行,它们就不会完全居中。
【解决方案2】:

根据 Scott 的想法(使用占位符),我能够使用 jQuery 和 CSS 创建这个解决方案:http://jsfiddle.net/9Qgsm/20/

仅使用占位符是不够的,因为当窗口达到一定宽度时,所有内容都会偏离中心。 jQuery 允许占位符根据包含的 div 的宽度出现或消失。 div 的最小宽度可以根据 div 中有多少个模块动态设置(我将使用 ColdFusion 完成该部分)。

jQuery:

$(document).ready(function(){ 
    //If the div creates more than one row of modules, add dummy divs
    if ($('#modulesAreaBlock').width()<625){
        $('.dummy').css('display','inline-block');
    }
});

$(window).resize(function(){
    //If the div creates more than one row of modules, add dummy divs
    if ($('#modulesAreaBlock').width()<625){
        $('.dummy').css('display','inline-block');        
    }
    //If the width of containing div contains all modules, hide the dummies
        if ($('#modulesAreaBlock').width()>=625){
        $('.dummy').css('display','none');
    }
});

CSS:

#modulesAreaBlock {
    margin-top: 50px;
    width:70%;
    margin-left: auto;
    margin-right: auto;
    position: relative; 
    text-align: center;
}

/*Displays the module blocks*/
.moduleBlock {
    text-align:center;
    height: 100px;
    width: 100px;
    margin-bottom: 2px;
    display: inline-block;
    zoom: 1;
    *display: inline;
    _height: 160px;
}

.dummy{
    display:none;
    width:100px; 
}

【讨论】:

    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2011-02-05
    相关资源
    最近更新 更多