2014-03-25 75 views
1

我想居中一個div元素,並將另一個div元素置於右側,並具有相同的垂直對齊。我不知道如何在不將兩個元素集中的情況下繼續下去。定位兩個div元素,其中一個居中

這是我的代碼。

<div class="container"> 
<div class="center"></div> 
<div class="right"></div> 
</div> 

.center { 
    width: 100px; 
    height: 100px; 
    margin: auto; 
    background-color: red; 
} 

.right { 
    width: 100px; 
    height: 100px; 
    background-color: blue; 
} 

http://jsfiddle.net/KWsnh/

回答

0

你可以使用calc要實現這一點:

FIDDLE

.container{ 
    text-align:center; 
    position: relative; 
} 
.center { 
    width: 100px; 
    height: 100px; 
    background-color: red; 
    display: inline-block; 
} 

.right { 
    width: 100px; 
    height: 100px; 
    background-color: blue; 
    position:absolute; 
    top:0; 
    left: calc(50% + 50px); // (100% - 100px)/2 + 100px (offset) = 50% + 50px 
} 

PS:Browser support for calc相當不錯,這些天。

0

Demo Fiddle

HTML

<div class="container"> 
    <div class='vcenter'> 
     <div class="center"></div> 
     <div class="right"></div> 
    </div> 
</div> 

CSS

html, body { 
    margin:0; 
    padding:0; 
    height:100%; 
    width:100%; 
} 
body { 
    display:table; 
} 
.container { 
    display:table-cell; 
    vertical-align:middle; 
} 
.center { 
    width: 100px; 
    height: 100px; 
    margin: 0 auto; 
    background-color: red; 
} 
.vcenter { 
    display:block; 
    width:100%; 
    position:relative; 
} 
.right { 
    width: 100px; 
    height: 100px; 
    background-color: blue; 
    position:absolute; 
    right:0; 
    top:0; 
}