什么是 Clearfix?
htmlweb developmentfront end technology更新于 2024/6/4 18:52:17
Clearfix,顾名思义,用于清除浮动。它通常用于浮动布局。Clearfix 被认为是清除浮动的一种 hack。
溢出问题
示例
在开始解决方案之前,我们先来看看问题所在。这里有一张图片,向右浮动。由于它比其所属元素高得多,它溢出了容器。-
<!DOCTYPE html> <html> <head> <style> div { border: 2px solid blue; padding: 5px; } .myimg { float: right; } </style> </head> <body> <h2>Demo Heading</h2> <p>We haven't used clearfix below:</p> <div> <img class="myimg" src="https://www.cainiaomax.com/machine_learning_with_python/images/machine-learning-with-python-mini-logo.jpg" alt="Machine Learning" width="150" height="150"> Etiam accumsan metus sapien, rutrum sagittis nunc posuere eu. Ut facilisis tortor eget justo scelerisque, quis porta nisl sagittis. </div> </body> </html>
输出显示溢出问题 -
使用 Clearfix 和溢出自动修复
示例
现在让我们使用 Clearfix 修复这个问题 -
<!DOCTYPE html> <html> <head> <style> div { border: 2px solid blue; padding: 5px; } .myimg { float: right; } .clearfix { overflow: auto; } </style> </head> <body> <h2 style="clear:right">Demo Heading</h2> <p>We have used clearfix below:</p> <div class="clearfix"> <img class="myimg" src="https://www.cainiaomax.com/machine_learning_with_python/images/machine-learning-with-python-mini-logo.jpg" alt="Machine Learning" width="150" height="150"> Etiam accumsan metus sapien, rutrum sagittis nunc posuere eu. Ut facilisis tortor eget justo scelerisque, quis porta nisl sagittis. </div> </body> </html>
使用 ::after 选择器修复 Clearfix 问题
示例
此处使用 ::after 选择器修复 Clearfix 问题 -
<!DOCTYPE html> <html> <head> <style> div { border: 2px solid blue; padding: 5px; } .myimg { float: right; } .clearfix::after { content: ""; clear: both; display: table; } </style> </head> <body> <h2 style="clear:right">Demo Heading</h2> <p>We have used clearfix below:</p> <div class="clearfix"> <img class="myimg" src="https://www.cainiaomax.com/machine_learning_with_python/images/machine-learning-with-python-mini-logo.jpg" alt="Machine Learning" width="150" height="150"> Etiam accumsan metus sapien, rutrum sagittis nunc posuere eu. Ut facilisis tortor eget justo scelerisque, quis porta nisl sagittis. </div> </body> </html>
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

