0

我想将 a放置在div另一个div位于屏幕中心的右侧,并带有margin-left: auto; margin-right: auto;.

我试图将两个 div 包装成一个似乎不起作用,因为它使包装器而不是第一个 div 居中。

有什么想法吗?谢谢!

到目前为止我的CSS代码:

#text {
width: 500px;
height: auto;
margin-left: auto;
margin-right: auto;
margin-top: 150px;
}

#image {
overflow: hidden;
float: right;
}
4

3 回答 3

1

谢谢你css;你也有html吗?

尝试拉动div包装的外部;你的定位应该有效。如果它继续给您带来问题,请尝试

{position: absolute;}
于 2012-12-19T15:29:08.960 回答
0

这有点骇人听闻,但这似乎运作良好(至少在 Chrome 中)。

<div style="position:relative; width:50%; border:1px solid black; margin-left: auto; margin-right: auto;">
    centered text
    <div style="position:absolute; left:100%; top:-1px; width:50px; border:1px solid red">
        right text
    </div>
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

外部的position: relative;属性div使内部 div 的绝对定位“相对于”外部 div。仅position: relative;在内部使用div会产生不同的结果(尽管您可能会付出一些努力)。

将内部定位divleft:100%;将内部的左边界div带到外部的右边界divtop:-1px;用于补偿外部div边界。如果你没有边界,top:0px;应该就足够了。width内部的可以div设置为外部div宽度的百分比。

我建议将它放入jsFiddle并使用属性,直到你得到它恰到好处。您还需要在您选择的目标浏览器中进行测试。

于 2012-12-19T15:37:39.227 回答
0

我想做到这一点的最好方法是在您的左侧 div 上使用一个边距,使其位于中心位置,然后将您的第二个 div 向左浮动以对接它,这样就可以了

<div style="position:relative;float:left;width:800px;margin:0 auto">
 <div style="position:relative;float:left;width:500px;margin:0 0 0 150px">
  This should go to the centre of the centred 800px div
 </div>
 <div style="position:relative;float:left;width:150px">
  This will be pushed up to the left of the centred 500px div
 </div>
</div>

我认为这不那么“hacky”......

于 2013-02-27T14:04:17.690 回答