你在寻找这样的东西吗?
HTML:
<div class="centered">This is some content in the centered DIV</div>
CSS:
.centered { background: #888; margin: 0 auto; width: 50%; }
使用margin: 0 auto
将使元素水平居中,这意味着它将具有“两边的边距相等”
使用上述方法时,您必须在元素上设置宽度,但如图所示,您可以使用百分比宽度(正如我想象的那样,您很可能会使用响应式布局)
但是,您不能在浮动元素上使用此技术,因此您可能希望在 CSS 中添加类似这样的内容:
.container { margin: 0 auto; width: 50%; }
如果我误解了您的问题,请告诉我。
编辑:针对下面的评论,我认为我已经成功实现了您正在寻找的东西,请参阅this fiddle
HTML:
<section class="header">
<div href="/" class="logo"><img src="/images/logo.jpg" /></div>
<div class="slogan"><img src="/images/slogan.jpg" /></div>
<div class="support"></div>
</section>
CSS:
.header { padding: 0 50px 0 300px; position: relative; }
.logo, .support { background: red; height: 50px; position: absolute; top: 0; }
.support { background: blue; right: 0; width: 50px; }
.logo { left: 0; width: 300px; }
.slogan { background: black; height: 50px; margin: 0 auto; width: 50px; }
The positioning/padding aspect of things isn't particularly pretty (if the width of .support or .logo change, you have to change that in the css) however I think this is the only safe way of doing it with pure HTML/CSS in a cross browser way (I'd be interested to see anyone elses take on it though), the important this is that it works and is completely valid.