CSS - 使用 float 的元素定位不起作用

标签 css css-float

我正在尝试定位两个面板,但无法正常工作...

我有一个包含两个面板的容器页面,每个面板都有自己的页面。我想使用 float 并排放置面板。

这是我的 CSS:

  .pages {width: 100%; position: absolute;}
  .leftPanel {position: relative; width: 25%; min-width:100px; float: left;}
  .rightPanel {position: static;}

和 HTML

  <div class="page">
    <div id="lefty" class="leftPanel">
      <div class="page">
        <p>helloworld</p>
      </div>
    </div>
    <div id="righty" class="rightPanel">
      <div class="page">
         <p>HELLO WORLD</p>
      </div>
    </div>    
 </div>

我必须对左面板使用position:relative,对右面板使用position:static。奇怪的是,这适用于 JSBin但在我的实际页面中,带有 position:static 的右侧面板始终具有覆盖整个屏幕的 100% 宽度。

关于我可能做错了什么的任何提示?

谢谢!

最佳答案

div 元素的宽度默认为父元素的 100%。由于您 float 了左手 div,因此您将其从流中移除,所以发生的情况是左手 div 实际上位于元素流之外。还 float 导致 div 收缩包装到它的 child 的大小。因此,如果您想要将右手 div 设置为与左手 div 相对,那么您应该做两件事:首先添加 float:left; position:relative; 到正确的样式。其次,您应该在其底部添加一个 div 以清除 float 。

另一方面,如果您打算以相同的方式设置多个元素的样式,您应该只使用类,否则只需为元素设置 ID 之外的样式。

  .pages {width: 100%; position: absolute;}
  .leftPanel {position: relative; width: 25%; min-width:100px; float: left;}
  .rightPanel {position: relative; float: left;}

  <div class="page">
    <div id="lefty" class="leftPanel">
      <div class="page">
        <p>helloworld</p>
      </div>
    </div>
    <div id="righty" class="rightPanel">
      <div class="page">
         <p>HELLO WORLD</p>
      </div>
    </div>
    <div style="clear:left;"></div>    
 </div>

关于CSS - 使用 float 的元素定位不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8317377/

相关文章:

javascript - 单击下一步按钮时如何更改事件阶段

html - 如何修复导航栏和下拉内容,使其对齐而不重叠?

css - 调整大小时背景图像消失

html - 文本不环绕一些 float 图像,在 IE 和 FF 中环绕,但在 chrome、safari 中不环绕

html - 使用 CSS 垂直格式化数学方程式 (5,343 + 32)

css-float - 在段落中居中图像

html - 段落内的 float 元素

css - 与伪元素水平对齐

javascript - 重新编码fly-out menu函数使parent LI的 "sticky"

css - 为什么这个非 float margin 会随着 float 而崩溃?