CSS定位居中加x像素

5

有没有办法仅使用 CSS 将一个 div 水平居中并向右移动x像素?

我现在有这些CSS代码:

#mydiv {
    display: block;
    width: 200px;
    margin: 200px auto;
}

我想将这个div定位到中心位置再向右移动300像素。是否可以只使用CSS实现?
(我知道有一种使用jQuery的方法,请参考此处,但我希望只使用CSS实现。)

你能详细说明你的问题吗? 另外,也许CSS calc可以帮助你: https://developer.mozilla.org/zh-CN/docs/Web/CSS/calc - shash7
IE支持对你来说很重要吗?使用CSS3(transform,calc...)有几种解决此问题的方法,但在一些较旧的浏览器中可能无法正常工作。如果您想要更广泛的浏览器支持而不使用CSS3,则我在下面提供了我的答案。 - Ronen Cypis
4个回答

4
你可以通过在 #mydiv 上添加 transform: translateX(300px); 来实现这一效果。
请查看 JSFiddle 上的 DEMO: DEMO
#mydiv {
    display: block; 
    width: 200px; 
    margin: 200px auto; 
    transform: translateX(300px); 
} 

2
是的,对于支持CSS3的浏览器来说是可以的,使用calc()函数实现。
#mydiv {
    display: block;
    width: 200px;
    margin-left: calc(50% + 200px); /* 50% - 100px (half of the div) + 300px */
}

    #mydiv {
      display: block;
      width: 200px; height: 50px;
      margin-left: calc(50% + 200px);
      /* 50% - 100px (half of the div) + 300px */
      background: blue;
    }
<div id="mydiv"></div>


1
首先,检查Fiddle Demo
如果您可以稍微调整HTML,那么不使用任何CSS3技巧也是可能的。诀窍是在屏幕中心(在此示例中为.container)上方放置一个大小为0X0像素的.wrapper元素,并在此包装器内定位您的.content并调整其'offset'(right/left属性)。
希望这有帮助 :-) HTML
<div class="container">
    <div class="anchor">
        <div class="content"></div>
    </div>
</div>

CSS
.container {
    background-color:red;
    position:relative;
    height:500px;
}
.anchor {
    position:absolute;
    top:50%;
    left:50%;
    width:0;
    height:0;
    overflow:visible;
}
.content{
    position:absolute;
    right:-100px; /* play with this to shift the content from the center... */
    width:200px;
    height:50px;
    background-color:blue;
}

0

像这个例子:https://jsfiddle.net/j6rnvdzp/

div {
    display: block;
    width: 200px;
    margin: 200px auto;
    background-color:red;
    position:absolute;
    right:-300px;
        left:0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接