2011-07-21 35 views
11

我试图在页面中心右侧放置一个div x的像素数量。因此,div将相对于中心。从中心偏移div

到目前为止,我已经试过像

margin:0 auto; 
margin-left:20px; 

一些愚蠢的但你并不需要测试在浏览器知道这是行不通的。

预先感谢任何帮助。

回答

15

我会尝试使用两个div,一个内另一个。例如:

<div class="outer"> 
    <div class="inner">Hello, world!</div> 
</div> 

.outer { 
    width: 1px; /* Or zero, or something very small */ 
    margin: auto; 
    overflow: visible; 
    background: red; /* A color just for debug */ 
} 
.inner { 
    margin-left: 20px; 
    background: yellow; /* A color just for debug */ 
    width: 100px; /* Depending on the desired effect, width might be needed */ 
} 

请参阅this example live at jsfiddle

div将被水平居中按本的问题/答案:How to horizontally center a <div> in another <div>?

然后,将内DIFF只是移动20个像素的右侧,使用裕度。

请注意,如果您将width作为auto,宽度将为零,并且可能不是您想要的。

+0

谢谢你的包,这很好。 –

+0

谢谢+1。这在标准化不同屏幕分辨率的弹出信息气泡位置时为我节省了一个实际问题。 –

+0

请注意,这仅适用于需要将内容向右移动的情况,因此如果您想将其移动到左侧,则不起作用。您可以通过使用负左边距来修复该问题,但会中断滚动。 – Vallentin

1

你可以居中DIV(含保证金:自动),并与移动内容(在另一个DIV)X像素的权利:

margin-right:-20px 

或者只是让你的封闭DIV 40个像素更长,调整您的文本向右

5

如果你知道你要相对于中心来定位div元素的宽度,那么你可以做这样的事情:

http://jsfiddle.net/UnsungHero97/Fg9n6/

HTML

<div id="box">off center</div> 
<div id="box2">center</div> 

CSS

#box { 
    width: 300px; 
    height: 100px; 
    border: 1px solid magenta; 
    margin: 0 auto; 
    text-align: center; 
    line-height: 100px; 
    position: relative; 
    left: 20px; 
} 
#box2 { 
    width: 300px; 
    height: 100px; 
    border: 1px solid skyblue; 
    margin: 0 auto; 
    text-align: center; 
    line-height: 100px; 
} 

结果

result

+1

这是正确的解决方案。你几乎可以钉住它:简单,优雅,与其他所有人不同,保持内容和表现的分离。做得好。 –

+1

这应该是接受anwser,迄今为止干净的解决方案 – Sonic750

+0

感谢,@ Sonic750! – Hristo

0

使用此代码:

<!DOCTYPE HTML> 
<html> 
    <head> 
     <title></title> 
     <style type="text/css"> 
      #outer { 
       position:relative; 
       width:300px; 
       height:100px; 
       background-color:#000000; 
      } 
      #inner { 
       position:absolute; 
       left:50%; 
       width:100px; 
       height:100px; 
       margin-left:-30px; /*Basic Margin Left-Half of Width=20px-50px=-30px*/ 
       background-color:#ff0000; 
      } 
     </style> 
    </head> 
    <body> 
     <div id="outer"> 
      <div id="inner"></div> 
     </div> 
    </body> 
</html> 

结果:
enter image description here

1
<code> 
<div class="col-xs-12 (or whatever the div is)" style="position:relative;left:20px;text-align:center">Your text here</div> 
</code> 

这适用于所有白手起家,HTML5(甚至MediaWiki的地狱)。该诀窍是“位置:相对的”

您可以像CSS一样执行相同的操作。

<code> 
.whateva { 
    position:relative; 
    left:20px; 
    text-align:center; 
} 
</code>