Html :before、:after和display:table的组合有什么作用?
我一直在钻研一个高质量的CSS表单 作者使用了很多这样的表达:Html :before、:after和display:table的组合有什么作用?,html,css,Html,Css,我一直在钻研一个高质量的CSS表单 作者使用了很多这样的表达: .clearfix:after, .clearfix:before, .product-slogan:after, .product-slogan:before { content: " "; display: table; } 我理解:在之后,内容,显示所做的事情,但我不理解它们共同实现的意义 我观察到,如果我关闭其中一些display:table,布局会发生很大变化。看起来,它们可以改变嵌套的框的布局行为,例如,
.clearfix:after,
.clearfix:before,
.product-slogan:after,
.product-slogan:before {
content: " ";
display: table;
}
我理解:在之后,内容
,显示
所做的事情,但我不理解它们共同实现的意义
我观察到,如果我关闭其中一些display:table
,布局会发生很大变化。看起来,它们可以改变嵌套的
框的布局行为,例如,如果一个框是float:left
,而其父框不是,则父框的高度将不会适应子框的高度。但是有了这个内容
和显示
定义,高度将采用,尽管子级本身不是display:table
所以问题是:有人能告诉我们一些关于这个“把戏”的细节或背景吗?这是一个“黑客”,就像著名的“明星黑客”,还是一个我现在看不到的很明显的东西
感谢您的时间和努力。这是micro clearfix黑客攻击的一部分,详细描述如下:
clearfix hack是一种流行的包含浮动的方法,无需使用表示标记。[…]
完整的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;
}
[…]此“micro clearfix”生成伪元素并将其显示设置为table。这将创建一个匿名表单元格和一个新的块格式上下文,这意味着:before伪元素可以防止顶部边距塌陷。:after伪元素用于清除浮动。因此,不需要隐藏任何生成的内容,所需的代码总量也减少了。[…]
这是micro clearfix黑客攻击的一部分,详细描述如下:
clearfix hack是一种流行的包含浮动的方法,无需使用表示标记。[…]
完整的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;
}
[…]此“micro clearfix”生成伪元素并将其显示设置为table。这将创建一个匿名表单元格和一个新的块格式上下文,这意味着:before伪元素可以防止顶部边距塌陷。:after伪元素用于清除浮动。因此,不需要隐藏任何生成的内容,所需的代码总量也减少了。[…]
@peter_the_oak有不同的清晰修复解决方案,您想使用哪种解决方案取决于具体情况。因为他们有不同的优点/缺点。@peter_the__oak Well高级代表帮不了多少忙。至少我不太在乎它。在这里有一个10k+代表的个人资料,他们给出了错误或不准确的答案,并且只得到了那个代表,因为他们给出了很多答案,而不是质量的原因。幸运的是,当我自己寻找答案时,我能够区分好答案和坏答案。@peter_the_oak有不同的清晰解决方案,您想使用哪一种取决于具体情况。因为他们有不同的优点/缺点。@peter_the__oak Well高级代表帮不了多少忙。至少我不太在乎它。在这里有一个10k+代表的个人资料,他们给出了错误或不准确的答案,并且只得到了那个代表,因为他们给出了很多答案,而不是质量的原因。幸运的是,当我自己寻找答案时,我可以区分好答案和坏答案。