2014-03-25 32 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; 
}