html - 在居中的动态宽度父级中左对齐子级

标签 html css

我有点想不通,也很难在网上/这里找到合适的解决方案,因为它很难制定。

基本上我想要的是像左对齐图像的居中对齐。所以它应该是一个居中的动态宽度父 div(宽度取决于浏览器宽度),它包含在一行中显示的带有图像的 div,但新行应该左对齐。

我很容易通过 Isotope 达到这个目标. 居中的砌体显示了我想要的行为。如果您调整浏览器的大小,父 div 将调整其宽度,子元素将重新定位并“填满一行”,保持“居中”。但未“填满的行”将保持左对齐。

有没有一种方法可以在不使用 js 或其他任何东西的情况下达到与 div 完全相同的行为(当然没有动画 ^^)?我希望我的意思很清楚。提前致谢!

最佳答案

我不知道这是否是结束这个问题的正确方法,但我要感谢所有回答我问题的人。所以我想不可能只用 CSS 来创建这种行为。需要 jQuery 或媒体查询才能获得正确的行为。

这是我最终解决问题的方法(实际使用 jQuery): http://jsfiddle.net/Ewtx2/

HTML

<div id='container'>
<div id='outline'>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
    <div class='innerbox'></div>
</div>
</div>

CSS

#container {
    width:100%;
    text-align:center;
    border: 1px red dashed;
}
#outline {
    text-align: left;
    font-size:0;
    display: inline-block;
    padding-left:5px;
    padding-bottom:5px;
    /* for ie6/7: */
    *display: inline;
    border: 1px black dashed;
    zoom:1;
}
.innerbox {
    display:inline-block;
    height:50px;
    margin-top:5px;
    margin-right:5px;
    width:50px;
    background:red;
}

jQuery

var boxAmount = 0;
var newWidth = 0;
setNewWidth();

$(window).resize(function() {
    setNewWidth();
});

function setNewWidth() {
    // get container width and check how many boxes fit into it (account margin/padding)
    boxAmount = ($('#container').width() - 5) / ($('.innerbox').width() + 5);
    boxAmount = Math.floor(boxAmount);
    // multiply the box amount with the box width to get the new width to hold the box amount + padding
    if(boxAmount <= $('.innerbox').length) { 
        newWidth = boxAmount * $('.innerbox').width() + boxAmount * 5; 
    }
    // set the new calculated width
    $('#outline').width(newWidth);    
}

我编写了一个脚本,它采用容器宽度,将其除以单个盒子的大小,然后将其平整,从而得出适合容器的盒子数量。然后它将这个框的数量乘以框的宽度,然后给我们新的轮廓尺寸。新尺寸设置为轮廓,因此带有所有框的轮廓始终保持居中,右侧不会出现奇怪的空白。

关于html - 在居中的动态宽度父级中左对齐子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17833757/

相关文章:

javascript - 计算jquery自动完成字段中多个选择的数量

html - 如何使用网格行对齐和网格列对齐?

html - 在图像上应用 <table>?

html - 用父元素的 beautifulsoup4 : does it affect the . 字符串解包元素?

javascript - 滚动到结束和开始时水平滚动添加类

javascript - 从引导导航栏链接中删除事件类

html - 如何调整 html 中 img 标签中使用的 svg 的大小?

javascript - div 在 click() 上不保留 CSS 属性

html - IE 中的样式问题 - 巨大的空间显示

css - 在带有图像背景的选择器之前的按钮中居中文本