[英]Using JavaScript to center multiple divs in a fluid layout
我正在尝试在容器div的中心对齐多个div。 我正在使用模数函数来计算页面左侧所需的填充。 这是我正在使用的JavaScript:
JavaScript的
window.addEventListener("resize", winResize, false);
var width, leftPad, space, boxWidth;
winResize();
function winResize() {
width = document.getElementById('body').offsetWidth;
boxWidth = 350 + 10 + 10;
space = width % boxWidth;
document.getElementById('a').innerHTML = width + '....' + space;
leftPad = space / 2;
document.getElementById('container').style.paddingLeft = leftPad + 'px';
document.getElementById('container').style.width -= leftPad;
};
HTML如下:
<div id="container">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</div>
和CSS :
#container {
width: 100%;
float: left;
}
#container .block {
width: 350px;
height: 350px;
background-color: 4e4e4e;
float: left;
margin: 10px;
}
我的问题是这段代码,左边的填充将容器div推到右边,这使页面比窗口更宽。 我试图从容器的宽度中删除填充(在winResize函数的最底行),但这似乎无济于事。 有没有办法用CSS填充/边距删除此“多余的div”?
我能感知到的是,您正在尝试使容器在页面的中心看起来,不需要js来执行,而是希望永远不要使用js在页面中放置静态元素。
这是您应该用来使其居中且流畅的CSS
#container {
width: 100%;
text-align:center;
}
#container .block {
width: 350px;
height: 350px;
background-color: #4e4e4e;
display:inline-block;
margin: 10px;
}
您也可以看到这个小提琴: http : //jsfiddle.net/ghFRv/
我想知道是否有任何原因要为什么要输入html元素?
这是CSS的工作,而CSS在这方面做得很好。
如果要使DIVS居中,可以使用margin: 0 auto;
在.block上。 这将使布局居中并保持元素块水平。
您的CSS看起来像这样:
#container {
width: 100%; /*Remove the float, it's not needed. Elements align top-left standard.*/
}
#container div.block {
width: 350px; /*Makes it possible for margin to center the box*/
height: 350px;
background: #4e4e4e; /*background is the shorthand version*/
margin: 10px auto; /*10px to keep your margin, auto to center it.*/
}
这应该可以解决您的问题,并且由于没有JS plus,因此页面加载速度更快,由于JS被禁用,因此无法“禁用”布局。
希望这会有所帮助,如果它没有忘记投票/接受答案的话
‐ Sid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.