【问题标题】:CSS Float explanationCSS Float 解释
【发布时间】:2011-11-01 09:51:44
【问题描述】:

CSS Float 让我抓狂了,谁能解释一下下面的情况?

如何重现:只需复制以下代码sn-p from

http://www.w3schools.com/css/tryit.asp?filename=trycss_float_clear

为什么没有clear:both 不起作用?

                <html>
                <head>
                <style type="text/css">
                .thumbnail 
                {
                float:left;
                width:110px;
                height:90px;
                margin:5px;
                }
                .text_line
                {
                display:block;
                height:90px;
                width:300px;
                margin:0px;

                background-color:red;
                }


                </style>
                </head>

                <body style="display:block">

                <h3>Image Gallery</h3>
                <p>Try resizing the window to see what happens when the images does not have enough room.</p>
                <img class="thumbnail" src="klematis_small.jpg" width="107" height="90">
                <img class="thumbnail" src="klematis2_small.jpg" width="107" height="80">
                <img class="thumbnail" src="klematis3_small.jpg" width="116" height="90">
                <img class="thumbnail" src="klematis4_small.jpg" width="120" height="90">
                <p class="text_line">a</p>

                <img class="thumbnail" src="klematis_small.jpg" width="107" height="90">
                <img class="thumbnail" src="klematis2_small.jpg" width="107" height="80">
                <img class="thumbnail" src="klematis3_small.jpg" width="116" height="90">
                <img class="thumbnail" src="klematis4_small.jpg" width="120" height="90">
                </body>
                </html>

【问题讨论】:

  • 似乎按预期工作。你能解释一下问题是什么,以及你想要达到的具体目标吗?
  • 对我来说,你拿走了一些东西(clear: both;)似乎真的很奇怪,然后你想知道它是如何不像 w3school 示例那样工作的。如果您删除或替换某些东西并且停止工作..您可能希望将其放回原处。
  • 作为记录,w3schools is bad,如果您想了解浮点数,floatutorial 可能是更好的资源。
  • 我试图了解“视觉格式化模型”的机制。 w3.org/TR/CSS2/visuren.html

标签: css css-float


【解决方案1】:

当您浮动一个块元素时,您是在告诉浏览器将其放置在前一个浮动对象旁边,只要容器足够宽(否则它将下降到前一个对象下方)。

当您浮动一个对象时,您实际上是将其从文档流中取出。浮动对象是父容器的一部分,但它的盒子模型样式(宽度、高度等)并未计算到父容器中。所以如果父容器中有一堆浮动元素,它的高度将等于零(如果高度不固定),因为浮动元素的高度被忽略了。

要解决这个问题,你需要清除浮动,这基本上意味着订单将恢复。

要么放一个带有 clear:both 的 div;在父容器的底部,或者把这个 clearfix 类放在父容器上:

/* Contain floats: nicolasgallagher.com/micro-clearfix-hack/ */ 
.clearfix:before, .clearfix:after { content: ""; display: table; }
.clearfix:after { clear: both; }
.clearfix { zoom: 1; }

这是一个非常简化的解释。在此处阅读有关浮动和清除的更多信息:http://dev.opera.com/articles/view/35-floats-and-clearing/

【讨论】:

    【解决方案2】:

    只需将 clear:both 放回(在 .text_line 中)

    【讨论】:

    • 其实我想要的是 float 是如何工作的?关于这个问题,为什么将“a”放在包含元素p之外?
    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    • 2020-10-09
    相关资源
    最近更新 更多