【问题标题】:Layout with relative positioning具有相对定位的布局
【发布时间】:2023-03-09 09:50:01
【问题描述】:

我想做这样的布局:

http://i.stack.imgur.com/uhgMg.jpg

#container
{
width:600px;
background:blue;
margin:0 auto;
}

.box
{
float:left;
width:196px;
height:318px;
background:red;
}

#box1
{
position:relative;
left:-140px;
float:left;
}

#box2
{
position:relative;
left:-102px;
}

#box3
{
position:relative;
left:-66px;
}

#box4 //this div is doing the mess because it's default position is under the other 3 divs and that's why the container stretches.
{
position:relative;
left:558px;
top:-318px;
}

<div id="container">

<div>RANDOM CONTENT</div>

<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
<div class="box" id="box4"></div>

<div style="clear:both"></div>
</div>

在某个容器中有 4 个彼此相邻的相对定位 div。

我图片中的红线显示了容器的高度应该在哪里结束,但它不是因为最后一个 div 的默认位置在那里。由于上面的随机内容,我无法为容器设置固定高度。

怎么做?

【问题讨论】:

    标签: css height css-position


    【解决方案1】:

    创建宽度不超过其包含元素宽度的 div。在这个例子中,你包含的 div 是 600 像素宽,但是你有 784 像素的元素,你试图在 float 中。如果你将它们更改为 148px 而不是 198px 你应该很好。

    虽然 - 我不确定您为什么要使用浮动和相对定位。相对定位相对于它通常在文档中流动的位置定位某些东西......我可能会坚持使用float:left; - 不需要相对定位。

    或者,如果您希望它们以这样的方式定位而不考虑其包含元素的宽度,只需使用绝对定位并完全放弃浮动和相对。

    【讨论】:

      【解决方案2】:

      为什么不分成3个部分

      <div id="container">
      
      <div class="cont">RANDOM CONTENT</div>
      <div class="banner">
        <div class="box" id="box1"></div>
        <div class="box" id="box2"></div>
        <div class="box" id="box3"></div>
        <div class="box" id="box4"></div>
      </div>
      <div style="clear:both"></div>
      <div class="cont">RANDOM CONTENT</div>
      </div>
      

      和css

      .banner {
          height: 318px;
          width: 800px;
          position: relative;
      }
      .cont {
      width:600px;
      background:blue;
      margin:0 auto;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-16
        • 2014-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多