2013-10-31 99 views
1

的較小的div內我想達到下述效果:http://jsfiddle.net/3KJta/1/如何水平居中可變寬度的較大的div,可變寬度

enter image description here

然而該解決方案我有使用已知寬度爲小的div和更大的div。我需要這個與變量大小的divs一起使用。這個用例是一個工具提示,出現在一個較小的靈活大小的元素上面。工具提示內容是未知的,所以寬度可以是任何東西。

到目前爲止,我有:

<div class="small"> 
    <div class="smaller"></div> 
    <div class="larger"></div> 
</div> 

* { 
    box-sizing: border-box; 
    margin: 0; 
    padding: 0; 
} 

div { 
    border: 2px solid black; 
} 

.small { 
    width: 50px; 
    height: 50px; 
    position: absolute; 
    left: 200px; 
    top: 50px; 
    text-align: center; 
} 

.smaller { 
    width: 20px; 
    height: 20px; 
    border-color: red; 
    display: inline-block; 
} 

.larger { 
    width: 200px; 
    height: 200px; 
    border-color: blue; 
    display: inline-block; 
    margin-left: -75px /* NOTE: in reality, .small has a variable width, and so does .larger, so i can't just take off this fixed margin */ 
} 

回答

0

如果您使用的和額外的元素,你可以做到這一點:

<div class="small"> 
    <div class="smaller"></div> 
    <div class="larger"> 
     <div>I'm extra</div> 
    </div> 
</div> 

CSS

.larger { 
    position:relative; 
    left:50%; 
    width:8000%; 
    margin-left:-4000%; 
    text-align:center; 
    border:none; 
} 
.larger div { 
    width: 200px; 
    height: 200px; 
    border-color: blue; 
    margin:auto; 
} 

http://jsfiddle.net/3KJta/4/

雖然這確實對內容比網頁寬度,所以你將與overflow:hidden需要這一切在一個容器中的一些問題:

http://jsfiddle.net/3KJta/7/

所有有點難看,但。也許有一種解決方案可以避免這樣做。也許是一個JS解決方案,它可以衡量您嘗試顯示並抵消它的內容的大小。

相關問題