欢迎来到HELLO素材网! 南京网站制作选择顺炫科技
丰富的DIV CSS模版、JS,jQuery特效免费提供下载
当前位置:主页 > 建站教程 > JS教程 >

图片浮动的怪异问题和解决方案

发表于2017-11-24 17:36| 次阅读| 来源网络整理| 作者session

摘要:当页面中两张图片都向同一个方向浮动,并且他们的距离很近时,会出现如右图的情况,我们称为“图片浮动的怪异

图片浮动问题-1

当页面中两张图片都向同一个方向浮动,并且他们的距离很近时,会出现如右图的情况,我们称为“图片浮动的怪异问题”。在我们的例子中,我们使用同一个class来为一组图片添加样式,

例如使用下面的CSS来给图片样式:

img.theremin { height: 370px; width: 300px; float: right; margin-left: 1em; }

例子的html结构如下:

<p>The theremin is one of the only truly new musical instruments created in the 20th century. Other instruments, such as the electric guitar and electronic synthesizer, were derived from existing classical forms, but the theremin, invented by Russian professor Léon Theremin, is completely novel. <img src="1.jpg" alt="Theremin performer" /></p> <p>It remains the only musical instrument that is not physically touched to produce a tone. Instead, musical pitches are generated by the musician’s interaction with two separate electric fields – one for frequency, the other for amplitude. A theremin performance is as much physical as it is musical, and <a href="#"> watching one</a> can be a mesmerizing experience.</p> <p>Sounds produced by the theremin are continuous and glissading, creating an “eerie” or haunting tone. The instrument was used to great effect in movies such as <cite>The Day The Earth Stood Still</cite>, <img src="2.jpg" alt="Gort, from The Day The Earth Stood Still" /> and in the Beach Boy’s <cite>“Good Vibrations”</cite>.</p>

图片浮动问题-2

它的结果就是和上面的截图效果一样。当浏览器的窗口变小,第二幅图片被向下挤压,直到和第一幅图片在垂直方向上平行,如右图所示。

为什么会出现这种情况呢?很简单,为一个元素应用float:right;意思是说:将该元素浮动到它随后内容的最右边。对于第一幅图片来说,它随后的内容包括第二幅图片。

要解决这个问题,我们需要修改第二幅图片的CSS样式。我们可以在原来的CSS上做些修改:

img.theremin { height: 370px; width: 300px; float: right; margin-left: 1em; clear: right; }

如果图片有各自不同的尺寸和不同的内联样式,我们只需要为第二幅图片增加clear: right;。在这个例子中,为所有的图片都添加clear: right;显得有点多余,第一幅图片不会受它影响,但它比单独为第二幅图片添加一个样式要精练得多。

clear是一个简单的属性,它可以有5个取值:left, right, both, inherit 和 none。它的大致意思是:在元素指定的方向上不允许浮动。在我们的例子中,图片都是右浮动的,我们不希望在它们的右边再出现任何东西,所以使用clear: right;来处理它们。

我们通常也会添加一个margin-bottom属性来分割图片,使它们之间有一些留白。

img.theremin { height: 370px; width: 300px; float: right; clear: right; margin: 0 0 2em 1em;}