2011-11-03 69 views
4

通常我会通过将margin设置为auto,使用position:absolute或通过填充来完成此操作,但不幸的是这些操作在这种情况下不起作用。我需要一个div从页面水平偏离中心大约15个像素。棘手的一点是,随着页面变宽,它需要正确缩放。在我看来,我需要根据中心点进行水平调整,而不是左侧。我怎么能做到这一点?谢谢。将div稍微偏离中心

+0

通过正确缩放你的意思是它必须与主格一起移动?或者您希望它(字面上)缩放,例如:如果屏幕为800px,则空间为15px,如果是1200,则为22px? – Yisela

回答

3

使用一个容器div,它是居中的,然后你的内容可以用gi已经margin-left:npx - 像这样:

HTML

<div id="container"> 
    <span id="green">&nbsp;</span><br /> 
    <span id="blue">&nbsp;</span> 
</div> 

CSS

#container{width:100px; margin:auto auto; background-color:red;} 
#container span{display:block; width:100%; } 
#green{background-color:green; margin-left:10px;} 
#blue{background-color:blue; margin-left:-10px;} 

看到例如编写了这里 - http://jsfiddle.net/Xpk8A/1/

+0

很多答案!最终这是我所做的最相似的一个,所以我猜你赢得奖品了。谢谢。 – keybored

+0

耶!谢谢。 – Alex

0

给出一个包装: margin:auto; position:absolute;

内包装,放div: 位置:相对; left:-15px; (或任何你想要的)

示例页面将有所帮助。

0

您可以绝对定位您的div并将left属性设置为50%。然后,将margin-left设置为50%+ 5px(无论如何)。但是,如果你在盒子上有一个固定的宽度,这只会起作用。例如,如果该框宽200px,则margin-left将是-115px

0

,关键是要设置width:100%和固定margin,你可以在我的例子见下文

<style> 
div { 
background-color:red; 
height:100px; 
margin:0 auto; 
width:100%; 
margin-left:15px; 
} 
</style> 

<div></div> 
0
<html> 
    <body> 
     <div class="centered"> 
      <div class="offcenter"> 
      </div> 
     </div> 
    </body> 
</html> 

的CSS将是:

.centered 
{ 
    margin: 0 auto; 
    width:300px; 
    height:200px; 
    background-color:red; 
} 

.offcenter 
{ 
    background-color:blue; 
    width:285px; 
    height:inherit; 
    float:right; 
} 

http://jsfiddle.net/evbbq/

0

可以使用display:inline-blockcenterDIV然后给你的margin它。

像这样:

.Parent{text-align:center;} 
.Child{ 
    display:inline-block; 
    text-align:left; 
    width:200px; 
    height:150px; 
    background:red; 
    margin-left:15px; 
} 

检查这个小提琴http://jsfiddle.net/Xpk8A/2/

删除margin-left:15px然后点击Run按钮,在小提琴看到不同的。