CSS-- Containing Floats

本文探讨了如何使用CSS浮动物元来创建灵活的网页布局,并解决浮动物元可能导致的布局问题。文章介绍了通过设置浮动物元的容器也具备浮动属性或者插入清除元素的方法来使容器能够包含其内部的浮动物元。

原文网址:http://www.complexspiral.com/publications

Containing Floats

As powerful and useful as they are, floats can make for tricky layout tools. Chances are that you may have seen something like the situation shown in Figure 1, which is accomplished with just two div elements, each with a floated image inside it.

Figure 1. That's not right!

This is probably not what the author had in mind, but given the styles used, it's the correct layout. Here's how we created it:

div.item {border: 1px solid; padding: 5px;}

div.item img {float: left; margin: 5px;}

That's all it takes. The result seen in Figure 1 happens because the div elements don't "stretch" to contain the floated images within them. To look at the situation from the reverse angle, it happens because the floated images "stick out" of the bottom of the div elements.

This is not a bug. It's also not a flaw in CSS. It is, in fact, the behavior that most authors will want most of the time. It's just not what they would want in the example shown in Figure 1.

Understanding the Problem

So when in the name of all that's good and right would authors want floats to stick out of their containing elements? Simple: in what is historically the most common case for float use. Consider Figure 2, and the basic markup structure that produced it.

Figure 2. Floating an image, flowing the text.

<p>

 ...text...

 <img src="jul31-03-sm.jpg" height="200" border="0" class="picture">

 ...text...

</p>

<p>

 ...text...

</p>

The practice of flowing text around an image goes back a long, long time. That's why the ability was added to the Web starting with Netscape 1.1, and why CSS makes it possible using the property float.[1] But look closely at Figure 2. The floated image is sticking out of its containing element. We can see this more clearly by adding borders to the paragraphs, as shown in Figure 3.

Figure 3. Adding borders to the paragraphs.

So now we can see why it's important that floats stick out of their containing elements. If they didn't, then Figure 2 would have looked like Figure 4 instead.

Figure 4. If floats expanded their ancestor elements.

That's something designers would never have accepted. So, in order to keep with Web design tradition and author expectation, CSS is written to allow floated elements to stick out of the bottom of their containing elements. While this is necessary for normal text flow, it's a major problem when floats are used for layout purposes.

A Clear Solution

If floats are to be used in creating non-table layouts, then there needs to be a way to make their containing elements stretch around them. At present, this requires a bit of a structural hack. Since we want the bottom of the containing element to be placed clear past the bottom of the float, then clear is our answer. We need only insert a block-level element just before the end of the container, and clear it. Consider:

<div class="item">

 <img src="w6144.gif">

 Widget 6144

 <br>$39.95

 <hr>

</div>

<div class="item">

 <img src="w6145.gif">

 Widget 6145

 <br>$44.95

 <hr>

</div>

Now we apply the following rules to the preceding markup, and get the result shown in Figure 5.

div.item hr {display: block; clear: left; margin: -0.66em 0;

  visibility: hidden;}

Figure 5. Using a horiztonal rule to force expansion.

By ensuring that the hr elements are block-level, part of the normal flow, and cleared, we force the divs to "stretch around" the left-floated images.

The negative top and bottom margins have the general effect of closing up the space that the hr occupies. However, this effect is not precise, and not necessarily identical across browsers. The semi-mysterious nature of horizontal rules makes it difficult to predict exactly what will happen. The effective height of the hr might be zero, or a small positive amount, or even a negative height.

Therefore, in situations where a precise clearing effect is needed, authors can use a div instead of an hr to create a clearing effect. For example:

div.clearer {clear: left; line-height: 0; height: 0;}

 

<div class="item">

 <img src="w6144.gif">

 Widget 6144

 <br>$39.95

 <div class="clearer">&nbsp;</div>

</div>

Set a Float to Fix a Float

There is a way to avoid over-use of the structural hacks discussed so far, although they are still necessary at times. In most browsers, and as defined in CSS2.1, a floated element will expand to contain any floated elements that descend from it. So in our widget example, we could remove all of the "clearer" elements and instead write these styles:

div.item {float: left; border: 1px solid; padding: 5px; width: 60%;}

div.item img {float: left; margin: 5px;}

Note that we've floated both the images and the "item" divs. By setting the width of the divs to be greater than 50%, we ensure that they will never be next to each other, but will instead stack up vertically. This has the result shown in Figure 6.

Figure 6. Using floats to stretch around floats.

This is obviously simpler to manage, both in terms of markup and style. However, the hacks discussed thus far are still useful. Suppose you want to put some advisory text underneath the items. In order to keep the text from flowing to the right of the items, we need to insert a clearing hack. This would lead us to create markup like the following, which is illustrated in Figure 7.

<div class="item">

 <img src="w6144.gif">

 Widget 6144

 <br>$39.95

</div>

<div class="item">

 <img src="w6145.gif">

 Widget 6145

 <br>$44.95

</div>

 <div class="clearer">&nbsp;</div>

 <p>Widgets are sold on an "as is" basis without

    warranty or guarantee.</p>

Figure 7. Floats and hacks get the desired layout.

The clearing div effectively pushes the normal flow downward, forcing any following content to flow after the cleared element, and therefore after the floated divs.

The potential drawback to using floats to contain floats is that you rely on browsers to consistently interpret the layout of multiple nested floated elements. The situation becomes more fragile if these floats are part of a more complicated layout, one possibly using floats, positioning, or tables. This is not to say such layouts are impossible to achieve. They may, however, involve a good deal of trial and error to avoid obscure floating and other layout bugs that may lurk inside rendering engines.

Summary

By understanding how floats and the normal flow relate to each other, and understanding how clearing can be used to manipulate the normal flow around floats, authors can employ floats as a very powerful layout tool. Because floats were not originally intended to be used for layout, some hacks may be necessary to make them behave as intended. This can involve floating elements that contain floats, "clearing" elements, or a combination of both.

Looking to the future, there have been a variety of proposed enhancements to CSS that would allow an author to declare that an element should stretch to contain any floated elements within itself. These would obviously be welcome additions to CSS, but as of this writing, support for such abilities is likely to be a long time coming.

  • [1] The term "float" refers to the way in which an element floats to one side and down, as described in the original "Additions to HTML 2.0" document that accompanied the release of Netscape 1.1.

 

 

内容概要:本文是一份针对2025年中国企业品牌传播环境撰写的《全网媒体发稿白皮书》,聚焦企业媒体发稿的策略制定、渠道选择与效果评估难题。通过分析当前企业面临的资源分散、内容同质、效果难量化等核心痛点,系统性地介绍了新闻媒体、央媒、地方官媒和自媒体四大渠道的特点与适用场景,并深度融合“传声港”AI驱动的新媒体平台能力,提出“策略+工具+落地”的一体化解决方案。白皮书详细阐述了传声港在资源整合、AI智能匹配、舆情监测、合规审核及全链路效果追踪方面的技术优势,构建了涵盖曝光、互动、转化与品牌影响力的多维评估体系,并通过快消、科技、零售等行业的实战案例验证其有效性。最后,提出了按企业发展阶段和营销节点定制的媒体组合策略,强调本土化传播与政府关系协同的重要性,助力企业实现品牌声量与实际转化的双重增长。; 适合人群:企业市场部负责人、品牌方管理者、公关传播从业者及从事数字营销的相关人员,尤其适用于初创期至成熟期不同发展阶段的企业决策者。; 使用场景及目标:①帮助企业科学制定媒体发稿策略,优化预算分配;②解决渠道对接繁琐、投放不精准、效果不可衡量等问题;③指导企业在重大营销节点(如春节、双11)开展高效传播;④提升品牌权威性、区域渗透力与危机应对能力; 阅读建议:建议结合自身企业所处阶段和发展目标,参考文中提供的“传声港服务组合”与“预算分配建议”进行策略匹配,同时重视AI工具在投放、监测与优化中的实际应用,定期复盘数据以实现持续迭代。
先展示下效果 https://pan.quark.cn/s/987bb7a43dd9 VeighNa - By Traders, For Traders, AI-Powered. Want to read this in english ? Go here VeighNa是一套基于Python的开源量化交易系统开发框架,在开源社区持续不断的贡献下一步步成长为多功能量化交易平台,自发布以来已经积累了众多来自金融机构或相关领域的用户,包括私募基金、证券公司、期货公司等。 在使用VeighNa进行二次开发(策略、模块等)的过程中有任何疑问,请查看VeighNa项目文档,如果无法解决请前往官方社区论坛的【提问求助】板块寻求帮助,也欢迎在【经验分享】板块分享你的使用心得! 想要获取更多关于VeighNa的资讯信息? 请扫描下方二维码添加小助手加入【VeighNa社区交流微信群】: AI-Powered VeighNa发布十周年之际正式推出4.0版本,重磅新增面向AI量化策略的vnpy.alpha模块,为专业量化交易员提供一站式多因子机器学习(ML)策略开发、投研和实盘交易解决方案: :bar_chart: dataset:因子特征工程 * 专为ML算法训练优化设计,支持高效批量特征计算与处理 * 内置丰富的因子特征表达式计算引擎,实现快速一键生成训练数据 * Alpha 158:源于微软Qlib项目的股票市场特征集合,涵盖K线形态、价格趋势、时序波动等多维度量化因子 :bulb: model:预测模型训练 * 提供标准化的ML模型开发模板,大幅简化模型构建与训练流程 * 统一API接口设计,支持无缝切换不同算法进行性能对比测试 * 集成多种主流机器学习算法: * Lass...
这个错误: ``` ValueError: Cannot mask with non-boolean array containing NA / NaN values ``` 通常出现在你试图使用一个包含 `NaN` 的布尔数组(Series)来进行条件筛选或赋值操作时,尤其是在使用 `pandas` 的 `DataFrame.loc` 或 `Series.where()`、`Series.mask()` 等方法时。 --- ## 🔍 错误原因 在 `pandas` 中,当你使用 `.loc[]`、`.where()` 或 `.mask()` 时,传入的索引或条件必须是一个 **布尔数组**(即每个值只能是 `True` 或 `False`),不能包含 `NaN`。 例如: ```python import pandas as pd import numpy as np df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [5, np.nan, 7, 8]}) # 错误示例:条件中包含 NaN df.loc[df['B'] > 6, 'A'] = 100 ``` 如果你运行这段代码,可能会遇到: ``` ValueError: Cannot mask with non-boolean array containing NA / NaN values ``` 因为 `df['B'] > 6` 的结果是一个包含 `NaN` 的布尔 Series: ```python print(df['B'] > 6) # 输出: # 0 False # 1 NaN # 2 True # 3 True # Name: B, dtype: object ``` 这会导致 `pandas` 无法进行索引操作。 --- ## ✅ 解决方法 ### ✅ 方法 1:使用 `fillna(False)` 或 `fillna(True)` 填充缺失值 ```python df.loc[df['B'].gt(6).fillna(False), 'A'] = 100 print(df) ``` 📌 说明: - `df['B'].gt(6)`:等价于 `df['B'] > 6` - `.fillna(False)`:将 `NaN` 替换为 `False`,表示这些位置不参与赋值 --- ### ✅ 方法 2:使用 `isna()` 过滤掉缺失值后再操作 ```python mask = (df['B'] > 6) & df['B'].notna() df.loc[mask, 'A'] = 100 print(df) ``` 📌 说明: - `df['B'].notna()` 确保只保留非空值 - `(df['B'] > 6) & ...` 确保逻辑正确 --- ### ✅ 方法 3:使用 `np.where` ```python import numpy as np df['A'] = np.where(df['B'].gt(6), 100, df['A']) print(df) ``` 📌 说明: - `np.where(condition, x, y)`:不会因为 `NaN` 报错,会自动处理缺失值 --- ## ✅ 示例完整代码 ```python import pandas as pd import numpy as np df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [5, np.nan, 7, 8]}) # 方法一 df.loc[df['B'].gt(6).fillna(False), 'A'] = 100 # 方法二 # mask = (df['B'] > 6) & df['B'].notna() # df.loc[mask, 'A'] = 100 # 方法三 # df['A'] = np.where(df['B'].gt(6), 100, df['A']) print(df) ``` --- ## ✅ 小贴士 | 方法 | 适用场景 | 是否自动处理 `NaN` | |------|----------|------------------| | `loc[condition]` | 简洁条件赋值 | ❌ 需要手动处理 `NaN` | | `np.where()` | 条件赋值 | ✅ 自动处理 `NaN` | | `Series.where()` / `Series.mask()` | 条件替换 | ❌ 需要处理缺失值 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值