4

What are good and recommended uses of percentage values for vertical CSS declarations?

In other words, under responsive design, are we overlooking something where % would be beneficial over em?


Because it seems that for most situations (except for cases where you want all sides equal; credit), em would be better served than %, consider:

Using percentages for the horizontal values of padding, margin or border of elements in CSS is fairly standard — especially in responsive web design. For example, take margin-left: 7.2% and padding: 0 5%. It also makes sense: the wider the screen, then the space will increase proportionally.

One can do the same for the vertical values:

margin-top: 5%;
padding: 10% 0;
border: 1% 0 2% 0;

As expected, an increasing viewport width will increase the corresponding vertical spaces.

However, in the cases I've come across, it can look a bit odd — unfitting to the design. It seems that em values may be better served.* But, on the other hand, where would it be beneficial to use percentages?


* Since these won't increase with the width of the screen, but will increase according to the font size of the page.

4

3 回答 3

2

Yes, depending on the situation just like any other css practice.

Say you have a container div that uses 100% of the screen height and you have a header you want to appear at the top of your div. You could say margin-top: 15px on your header, which works, but then if I come and view it on my phone it will look very squished.

So instead you say margin-top: 10% then no matter what screen I come and view your site on your header is always 10% from the top of the div. which means the relative flow of your layout will always be the same.

The general rule is this: For any valid css you can write there is a use-case where it would be the best way to go about achieving your design goal. Forget anyone who says "Never use negative margins" or "always avoid absolute positioning" or any of the other crap they throw around.

于 2012-12-03T15:43:57.280 回答
2

我不认为这个问题有任何正确或错误的答案。这确实取决于您的设计。

正如您所指出的,% 值,即使在边距和填充的基于垂直的属性上,仍然与文档的宽度相关。因此,如果您的设计需要均匀的填充,那么所有的 % 值都很棒。

但是,如果设计是面向内容的,并且您仍然在水平属性上使用 % 值进行响应式设计,则 % 可能不是垂直属性的最佳选择。例如,您可能希望padding-top恰好是 1 行文本的高度。所以你会使用ems.

但我离题了;这确实取决于您的设计和个人喜好。

于 2012-12-03T15:43:08.840 回答
0

我最近也一直在思考这个问题,在网上阅读后,我开始依赖的“经验法则”如下。首先,为什么 % 是水平轴的良好响应式设计的原因是因为众所周知,浏览器的宽度可能会因用户使用手机还是计算机而有很大差异。然而,垂直轴是不同的,因为虽然它也可以像水平轴一样变化,但许多网页都是为垂直滚动而创建的,并且用户希望向下滚动。在这种情况下,由于 ems 响应速度较慢,因此垂直滚动多一点是可以的。

要基于该假设回答您的问题,您将使用 % 作为垂直边距的时间是当您有一个设计时,您不想让用户滚动太多以查看页面的一部分。具体示例可能是您不希望任何滚动的单页 Web 应用程序或标题或初始页面内容,例如您希望用户无需向下滚动即可完整查看的图片。

于 2015-04-24T15:45:45.633 回答