After unexpected gaps in pages, perhaps the most common layout problem is content overflow. Thankfully, there are just a few common causes of this problem, and some well-established solutions:
The reason is fairly straightforward: by default, containers will automatically be the height of their content. By setting a default height on the element, you are subverting this rule. The other relevant rule is that browsers will always show content that overflows by default. Thus, you get the result shown in Figure 1.
Remove the height from the container’s CSS, and let the element find its own natural height from its content.
从容器CSS中删除height ,然后让元素从其内容中找到其自身的自然高度。
Remove the border (or background) from the element: no border, no visual overflow! *
从元素中删除border (或background ):无边框,无视觉溢出! *
Setting overflow: scroll-y on the container is almost never a solution: having a scrolling window inside another scrolling window (the browser) is a recipe for user confusion and frustration).
An image placed on a web page will appear at its natural width: for a bitmap, this means the image’s horizontal pixel count; for an SVG, the value of its predefined height and width attributes. This causes overflow in any element that is too small to contain it, as shown in Figure 2.
The solution is almost always the same: provide a percentage width for the image in CSS:
解决方案几乎总是相同的:在CSS中为图像提供百分比宽度:
img { width: 100%; }
This will make the image always fit its responsive parent.
这将使图像始终适合其响应父级。
You can find more information about these techniques in my Fluid Images and SVG Images articles; you should also consider picture and srcset for responsive bitmap images.
溢出原因4:不使用边框 (Overflow Cause 4: Not Using Border-Box)
By default, width in CSS is not what most people assume it is: padding is added to the width of content to produce an overall width, often causing overflow issues.
Engage box-sizing: border-box for most or all elements by default. Doing this at the start of your site development is very important; otherwise, you’ll be building and measuring elements based on a series of incorrect assumptions, and will be forced to change them all later.
Floated elements to not contribute to the height of their container. Taking the following as an example:
浮动元素不会增加其容器的高度。 以以下为例:
<div id="levee">
<img src="chicago.jpg" alt="A photograph of the waterfront
of Chicago">
<p>Thinkin bout me baby and my happy home<br>
Going, gon to chicago,<br>
Gon to chicago,<br>
Sorry but I cant take you.<br>
Going down, going down now, going down.
<p>Photograph by
<a href="https://www.flickr.com/photos/snake_bill/13812951923/">
Yulin Lu</a>, used under a Creative Coommons
Attribution-NonCommercial-NoDerivs 2.0 Generic license.
</div>
There are many “clear floats” or “clearfix” solutions for this problem. The simplest solution is extremely effective, but also counter-intuitive: use overflow: hidden on the parent element. In practice, this does the opposite of what you might expect: