您好 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 个子元素,我的父元素应该始终居中。
子元素的宽度应该影响父元素的宽度
这就是我的
这就是我得到的
这就是我想要的(看到父宽度根据子元素减小)
fiddle
最佳答案
您需要一些 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/