html - 在未知宽度的父容器中集中对齐固定宽度的子元素

标签 html css

您好 HTML/CSS 开发人员! 陷入一个奇怪的场景 将尝试通过图像解释我的查询。 需要它至少在 IE 8 或 9 中工作。

积分: 这是一种响应式布局的方法,

.container {width:100%;margin-left:auto;margin-right:auto;display:block;}
.parent-container {width:auto;overflow:hidden;margin:0 auto;display:block}
.child-element {width: 285px;float:left
}

层次结构 .container > .parent-container > .child-element

标签: 我有一个 100% 的容器

在里面,我有一个父容器{没有声明宽度(红色背景色)} 在里面我有固定宽度的子元素。

我想要的是,无论我的屏幕尺寸是多少,如果有空间容纳 3 个子元素或 4 个子元素,我的父元素应该始终居中。

子元素的宽度应该影响父元素的宽度

这就是我的

This is what I have

这就是我得到的 This is what I'm getting

这就是我想要的(看到父宽度根据子元素减小) This is what I need

fiddle

http://jsfiddle.net/happy2deepak/9wm7ppwL/2/

最佳答案

您需要一些 javascript 来根据窗口宽度更新父容器的宽度,您可以通过将窗口宽度除以子宽度(包括填充和边距)来完成,并取最大可能的子容器,即除法结果的底部

function setContainerWidth(){
    var childWidth = 305, 
        winWidth = $(window).width(), 
        parentContainer = $('body').find('.parent-container'), 
        minChildren,
        containerCalculatedWidth;

        minChildren = Math.floor(winWidth / childWidth);
        parentContainer.css("width", minChildren * childWidth);
}

setContainerWidth();

$(window).resize(setContainerWidth);

一个fiddle看看它是如何工作的。

关于html - 在未知宽度的父容器中集中对齐固定宽度的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28456774/

相关文章:

python - 如何在html文档中使用for循环

css - 在div中间显示图像

css - 带有 CSS 的箭头框

html - 无法使 Bootstrap 模板中的 CSS 边距消失

javascript - 如何通过点击页面上的按钮触发服务器发送SSE?

jquery - Swiper slider 在 Bootstrap 选项卡面板内不起作用

html - 如何使用 HTML/CSS 获取标题左侧的复选框

css - 样式被 URL 中的哈希搞砸了

java - 导航菜单中不同帐户类型的不同菜单

javascript - Canvas 越大,移动越慢