2015-04-04 39 views
1

我一直在挖掘高质量的CSS表格。这个组合:before,:after和display:table做什么?

笔者使用了大量的表情像这样的:

.clearfix:after, 
.clearfix:before, 
.product-slogan:after, 
.product-slogan:before { 
    content: " "; 
    display: table; 
} 

我明白了什么:aftercontentdisplay做,但我不明白的是什么,他们一起实现的意义。

我观察到,如果我关闭其中一些display: table,布局会发生很大变化。看起来,他们可以改变嵌套的<div>框的布局行为,例如,如果一个盒子是float: left并且它的父母不是,那么父母的身高不会适应孩子的高度。但有了这个contentdisplay的定义,高度会采用,虽然孩子本身不是display:table

所以问题是:有人可以告诉一些关于这个“技巧”的细节或上下文吗?这是一个“黑客”,就像着名的“明星黑客”,还是它显得很安静,我现在只是看不到?

谢谢您的时间和精力。

回答

4

正是在这里详细描述的微clearfix黑客的一部分:nicolasgallagher.com: A new micro clearfix hack

的clearfix黑客是遏制浮动,而不诉诸使用表象标记的流行方式[...]

完整的clearfix是:

/** 
* For modern browsers 
* 1. The space content is one way to avoid an Opera bug when the 
* contenteditable attribute is included anywhere else in the document. 
* Otherwise it causes space to appear at the top and bottom of elements 
* that are clearfixed. 
* 2. The use of `table` rather than `block` is only necessary if using 
* `:before` to contain the top-margins of child elements. 
*/ 
.cf:before, 
.cf:after { 
    content: " "; /* 1 */ 
    display: table; /* 2 */ 
} 

.cf:after { 
    clear: both; 
} 

/** 
* For IE 6/7 only 
* Include this rule to trigger hasLayout and contain floats. 
*/ 
.cf { 
    *zoom: 1; 
} 

[...]这种“微clearfix产生伪元素,并设置它们的显示表。这将创建一个匿名表格单元格和一个新的块格式上下文,这意味着:before伪元素可以防止顶点边距崩溃。之后:用伪元素清除浮点数。 [...]

+0

非常感谢,这是有帮助的:-)打开了一些门给我.. .. – 2015-04-04 10:10:45

+0

@peter_the_oak在那里有不同的清晰解决方案,您要使用哪一个取决于具体情况。因为它们有不同的优点/缺点。 – 2015-04-04 10:15:46

+0

嗯,你刚刚结束了6K代表:-)祝贺;-)有很好的复活节...... – 2015-04-04 10:24:08