简体   繁体   English

使左右浮动div不可调整大小

[英]make left and right floated div not resizable

I have 3 div's: 我有3个div:

.left, .right {
    width: 30px;
    resize: none;
}
.left {
    float: left;
}
.right {
    float: right;
}
.center {
    max-width: 960px;
    margin: 0 auto;
}

What I want to achieve is that only the middle one resizes when resizing the browser. 我要实现的是在调整浏览器大小时仅调整中间的大小。 In the left and right div there is an image that is part of the design. 在左和右div中有一个图像是设计的一部分。

When I make the browser smaller, the left en right div will narrow at one point and it seems that it is getting pushed into the center div. 当我缩小浏览器的尺寸时,左侧和右侧的div会在某一点变窄,并且似乎正被推入中央div。 This makes the content of the center being pushed down. 这使得中心的内容被下推。 How can I make sure the 2 div will stay @30px? 如何确定2格保持@ 30px?

Strange thing is, in the jsfiddle it does work... 奇怪的是,在jsfiddle中它确实可以工作...

jsfiddle 的jsfiddle

The issue is with the <img /> element you have in the header. 问题出在标题中的<img />元素。 When you hide it you can see that it no longer interferes with your layout. 隐藏它时,您会发现它不再干扰您的布局。

The problem is because the <img /> element will expand to the maximum size of the container, which is 100%. 问题是因为<img />元素将扩展到容器的最大大小,即100%。 That 100% does not include the 30px you have reserved for each side, as floated elements are taken out of the document flow. 由于浮动元素将从文档流中取出,因此100%不包括为每一边保留的30px。 Declaring 100% of a child element means it will expand to the width of its parent elements, without taking into account the extra space taken up by floated siblings. 声明100%的子元素意味着它将扩展到其父元素的宽度,而不考虑浮动兄弟姐妹占用的额外空间。 Therefore, a solution would be using CSS calc to constrain the width of .center , and float it to the left, too: 因此,一种解决方案是使用CSS calc来限制.center的宽度,并将其向左浮动:

.center {
    width: calc(100% - 60px);
}

Alternatively, you can give .center a margin of 30px on the left and on the right. 另外,您也可以在.center的左边和右边留出30px的空白。 The floated divs will ignore margins because they are taken out of the document flow, and will fit perfectly within that 30px corridor you have created for them. 浮动的div将忽略边距,因为它们已从文档流中删除,并将完全适合您为其创建的30px走廊。

.center {
    margin: 0 30px;
}

Both methods I have tested and verified by playing with the Inspector on the link you have provided. 我通过在您提供的链接上与Inspector一起进行测试来测试和验证这两种方法。 The calc() method might suffer from lack of support in older browsers, while the margin method will work for most browsers that are in use today :) pick any one. calc()方法可能会在较旧的浏览器中缺乏支持,而margin方法将适用于当今使用的大多数浏览器:)选择任何一种。

Try setting the horizontal margin for your center div to the known width of the left and right divs: 尝试将中心div的水平边距设置为左右div的已知宽度:

.center {
    max-width: 960px;
    margin: 0 30px;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM