具有相对定位的布局
我想制作这个布局:
https://i.sstatic.net/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 的默认位置在下面,所以它没有结束。由于上面的随机内容,我无法设置容器的固定高度。
怎么做呢?
I want to make this layout:
https://i.sstatic.net/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>
There are 4 relative positioned divs next to each other in some container.
The red line in my picture shows where the container's height should end but it doesn't because of the last div which default position is down there. I can't set fixed height for container because of random stuff above.
How to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建宽度加起来不超过其包含元素的宽度的 div。在此示例中,您的包含 div 宽 600 像素,但您尝试
浮动
的元素有 784 像素。如果您将它们更改为148px
而不是198px
你应该很好。不过 - 我不确定你为什么要使用浮动和相对定位。相对定位将某些内容相对于文档中通常流动的位置进行定位...我可能会坚持使用 float:left; - 不需要相对定位。
或者,如果您希望它们像这样定位,而不管其包含元素的宽度如何,只需使用绝对定位并完全删除浮动和相对。
Create divs that don't have widths that add up to more than the width of their containing element. In this example, your containing div is 600 pixels wide, but you have 784 pixels worth of elements you're trying to
float
in. If you change them to148px
instead of198px
you should be good.Though - I'm not sure why you're using float AND relative positioning. Relative positioning positions something relative to where it would normally flow in the document... I would probably just stick with
float:left;
- there shouldn't be a need for relative positioning.Or, if you want them to be positioned like that regardless of the width of their containing element, just use absolute positioning and drop float and relative altogether.
为什么不分成 3 部分
和 css
why not to divide into 3 sections
and css