0

所以我只是想掌握这个概念。在下图中,您可以看到子元素的总宽度为 250 像素,它们都被 10 像素的填充包围。所以要获得百分比,我们需要做目标/上下文。我不明白的部分是,要获得总宽度(250px)的百分比,我们根据父级的总宽度(590px)计算它,但是要计算填充的百分比(10px),我们这样做是基于父母的内部宽度(570px)..那为什么?或者更具体地说,为什么不是从 570px 计算 250px 百分比,因为看起来 570px div 的填充没有限制 250px 块占用的空间。我在这里想念什么?

在此处输入图像描述

4

1 回答 1

1

I found that diagram a bit confusing and it's hard to answer your question using it alone, I hope this example I've mocked up will help (usually easier to look at live code) - be sure to read the source and examine the size of the individual elements using Chrome Developer Tools (the Metrics section and simply hovering over the individual <div>s with the Elements tab open) or your browser's equivalent.

In the diagram, they've used percentages but have confused things by rounding them; never round percentages up/down when doing responsive design, just use the exact figure (or if you're drawing a diagram, show the target and context calculation), browsers (with some ancient exceptions) can always cope with multiple decimal places. (Ideally you'd use a CSS pre-processor like SASS which will do the maths for you).

Also, I've simplified things by just having two columns and floating them left/right, I think the third central 20px column in the drawing makes it harder to understand. Get it working with equal left/right padding for everything first then worry about the more complex stuff, only use a third div if you actually need something inside it.

You also need to be aware of the box-model - the sub elements width is 250px, but if have a 250px wide box and use CSS to add 10px padding either size, the display width will be 270px because it's the width (or height), plus any border, plus padding. This can get really confusing - what you actually want is something that's still 250px wide with 10px left/right padding within it - often it's easier to turn this behaviour off - as in my example - with box-sizing: border-box; (there's a Mozilla prefix needed).

You always use the parent (the element's container) for the context when setting flexible margins or padding. You may note that I've used 570 rather than 590 in the calculation for .rectangle because 570px is the effective width you have to work with for Column 1, the 20px is just padding on either side, I'm still looking at the parent element though, nothing else. The rectangles also have left/right margins to space things out; you could remove those or replace with, say, a right-only margin on the first rectangle if you wanted to have it flush with the column text.

Hope this helps…</p>

于 2013-07-19T07:12:52.917 回答