Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

css float - Clear fix and uncollapse margins with CSS without side effects?

What's a general good way to clearfix and uncollapse margins with CSS without side effects (nor additional HTML elements)?

The following cause side effects (and would like to avoid them):

  • Setting overflow: hidden or overflow: auto: Clips box-shadow, CSS transforms, and other content one may want to show outside the box. Thus it can't be used in several cases (but otherwise works great).
  • Setting border or padding: Obvious positioning/sizing effects.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The clear and collapse fix, based on this clear fix, with added margin uncollapse:

.group:before, /* :before to uncollapse the top margin */
.group:after{
    display: block;
    clear: both; /* clear fix */
    content: "a0 "; /*   - just a space doesn't uncollapse margins */
    visibility: hidden; /* make sure not to show anything */
    height: 0;
}
.group{
    zoom: 1; /* solves it all for IE < 8, and doesn't hurt other browsers */
}

Demo: jsFiddle, IE7 render with netrenderer

Note that content: "a0 "; is equivalent to &nbsp; and is used instead of a non-whitespace character (eg .) so that when you select the block and copy it, you do not get extra visible characters, which otherwise happens in some browsers (for example IE9).

The drawbacks with this solution are:

  • :before and :after are defined, so special care needs to be taken if they are to be used.
  • For every new selector you want to have this fix applied to you have to specify the selector 3 times.
  • Not very short/trivial.

A similar solution is used by YUI, described in this article (but without &nbsp;).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...