我正在尝试获取 div #primary
坐在页面中间 position: relative
和 margin: 0 auto
,我也想要一个 <aside>
直接位于 #primary
右侧的元素并且不会在调整宽度时四处移动。
与 margin: 0 auto
,我在 Chrome/Firefox 开发者工具中注意到这有效地给出了 #primary
两边都有完整的边距,防止任何东西进入该空间。
我试过给 #primary
float: left
, 但这似乎抵消了 margin: 0 auto
并制作#primary
与页面左侧齐平。
我怎样才能达到这个效果?谢谢。
#content {
margin: 0 auto;
width: 100%;
}
#primary {
position: relative;
width: 900px;
margin: 0 auto;
}
aside {
width: 350px;
float: right;
}
<div id="content">
<div id="primary"></div>
<aside></aside>
</div>
最佳答案
只需将 aside
above/before 放置在您的 HTML 代码中居中的 DIV(我更改了元素的尺寸以使其适合代码段窗口):
#content{
margin: 0 auto;
width: 100%;
height: 500px;
background: yellow;
}
#primary{
position: relative;
width: 300px;
height: 300px;
margin: 0 auto;
background: red;
}
aside {
width: 100px;
height: 200px;
float: right;
background: green;
}
<div id="content">
<aside>aside</aside>
<div id="primary">primary</div>
</div>
关于css - 带边距的 Div : 0 auto preventing another Div from floating to the right of it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47877748/