2014-02-27 194 views
1

請考慮下面的例子:定位的div位置:絕對元素

http://jsfiddle.net/AsGk4/

正如你可以看到兩個箱子重疊,而不是被定位爲緊挨彼此float:left財產。當我刪除小孩.text DIV時,這些框顯示爲他們應該。我認爲這種行爲來自.textposition:absolute屬性,但爲什麼這會影響父DIV的外觀?

HTML

<div class="box"> 
    <div class='text'><span>Some text</span><div> 
</div> 

<div class="box"> 
    <div class='text'><span>Some text</span><div> 
</div> 

CSS

.box { 
    position: relative; 
    display:inline-block; 
    width:100px; 
    height:100px; 
    background-color:#0000FF; 
    float:left; 
} 
.box:before { 
    content:''; 
    position: absolute; 
    left: 1%; 
    top: 1%; 
    width: 98%; 
    height: 98%; 
    border: 1px solid white; 
} 
.text { 
    position: absolute; 
    bottom:9px; 
    left:5px; 
    width: 95%; 
    text-align:left; 
} 
.text span { 
    color: white; 
    font: bold 12px/16px Helvetica, Sans-Serif; 
    background: rgb(0, 0, 0); 
    /* fallback color */ 
    background: rgba(0, 0, 0, 0.7); 
    padding: 1px; 
    padding-left:3px; 
    padding-right:1px; 
} 

編輯:

我傻了,忘了關閉div標籤。道歉。

回答

1

首先,如果你使用的是display: inline-block;反之亦然如果你正在使用float你不需要float: left; ..

然後不要忘記clear他們,如果你與display: inline-block;堅持那麼我想您將需要vertial-align: top;,因爲它們默認與基線對齊。因此,使用任何一個,因爲同時使用似乎是多餘的

另外值得注意的是使用display: inline-block;會導致你的空白

又有什麼問題?您正在關閉您的div標籤,there are many ways to deal with that

Demo


如果你想重構你的代碼,下面的代碼片段

padding: 1px; 
padding-left:3px; 
padding-right:1px; 

可以寫成padding: 1px 1px 1px 3px;這不過是簡寫語法

+1

Voopsy,傻我!如果你連續兩天沒有睡覺,情況就會如此。道歉。 – astralmaster

1

關閉文本divs,它工作得很好。

<div class="box"> 
    <div class='text'><span>Some text</span></div> 
</div> 

<div class="box"> 
    <div class='text'><span>Some text</span></div> 
</div> 

updated Fiddle

+0

Voopsy,我傻!如果你連續兩天沒有睡覺,情況就會如此。道歉。 – astralmaster

1

您的交易<div>標籤不打烊 - 你需要將其更改爲</div>。這導致盒子相互嵌套,而不是並排放置。