2012-07-24 95 views
0

我试图创建一个包装在其中4个div彼此相邻(两个彼此相邻,下方是剩下的两个)。然而问题是,是否只有第四个正在显现。我试过设置溢出:隐藏,玩具与显示属性,并试图使用float:left和float:right。但迄今为止没有运气。将四个div放在一个包装中,只有一个显示自己

这是我使用的CSS:

html, body{ 
width: 100%; 
height: 100%; 
} 

#wrapper{ 
width: 60%; 
height: 60%; 
top: 20%; 
left: 20%; 
position: relative; 
overflow: hidden; 
border: 1px solid #000; 
} 

#one{ 
background-color: red; 
width: 50%; 
position: absolute; 
height: 50%; 
} 

#two{ 
background-color: green; 
width: 50%; 
position: absolute; 
height: 50%; 
} 

#three{ 
background-color:blue; 
width: 50%; 
position: absolute; 
height: 50%; 
} 

#four{ 
background-color: yellow; 
width: 50%; 
position: absolute; 
height: 50%; 
} 

,这是html代码与它去:

<html><head> 
<link rel="stylesheet" type="text/css" href="style.css"/> 
</head><body> 
<div id="wrapper"> 
    <div id="one">a</div> 
    <div id="two">b</div> 
    <div id="three">c</div> 
    <div id="four">d</div> 
</div> 
</body></html> 

谁能弄清楚为什么黄(四)个DIV是唯一一个显示自己,即使我让它正确地浮动和其他人离开? (除此之外,我还想知道为什么滚动条出现的原因是宽度:100%,身高部分为100%)。

回答

1

这是因为您将所有四个div设置为绝对位置。然后您必须使用顶部,底部,右侧或左侧来定位它们。当你完全放置一个元素时,它会被取出文档的流程。

jsFiddle example

CSS

#one{ 
background-color: red; 
width: 50%; 
position: absolute; 
height: 50%; 
} 

#two{ 
background-color: green; 
width: 50%; 
position: absolute; 
height: 50%; 
right:0; 
top:0; 
} 

#three{ 
background-color:blue; 
width: 50%; 
position: absolute; 
height: 50%; 
left:0; 
bottom:0; 
} 

#four{ 
background-color: yellow; 
width: 50%; 
bottom:0; 
right:0%; 
position: absolute; 
height: 50%; 
} 

的第二个选项是去除绝对定位,浮动他们都离开了。

jsFiddle example

CSS:

#one,#two,#three,#four { 
float:left; 
} 
​ 
+0

到底会发生什么,然后,如果它从流去掉? – Gooey 2012-07-24 14:59:26

+0

它们位于具有位置集的第一个父代的左上角。 – j08691 2012-07-24 15:00:07

2

浮法您的内部元素。在这里看到:

http://jsfiddle.net/dkGBA/1/

的主要变化:

.child 
{ 
    width: 50%; 
    height: 50%; 
    float: left; 
} 

<div id="one" class="child">a</div> 
<div id="two" class="child">b</div> 
<div id="three" class="child">c</div> 
<div id="four" class="child">d</div> 
1

不要使用位置这一点,而是使用浮动。

例子:

http://jsbin.com/ucofed/edit

+0

有趣的是,我将在这个浮动示例上搜索一些读物。 – Gooey 2012-07-24 15:05:59