我想将一个宽度未知的 DIV 居中。它应该与实际内容一样宽。我试过了:
<div style="background-color: red; width: 300px; text-align: center; margin: 0 auto;">dsffsffsfsddf</div>
它仅在设置“宽度”时有效。Auto
不会有帮助。
这很简单(http://jsfiddle.net/bukfixart/tYyJN/):
<div style="border:1px solid #000;text-align:center;">
<div style="border: 1px solid #f00; display:inline-block;">some content</div>
</div>
重点是text-align:center
外盒和display:inline-block
内盒
看看我的小提琴:http: //jsfiddle.net/PRUBd/
CSS
body {
text-align: center;
}
#container {
text-align: left;
border: 1px solid black;
padding: 10px;
display: inline-block;
}
HTML
<div id="container">
This div is as wide as its content and centered!
</div>
display: table; margin: 0 auto;
div{
display:table
margin:0 auto;
}
看看这个先前的答案:centering variable width divs
但一个答案是基本上使用 css-floats
<style type="text/css">
#hideoverflow { overflow: hidden; }
#outer { position: relative; left: 50%; float: left; }
#inner { position: relative; left: -50%; float: left; }
</style>
<div id="hideoverflow">
<div id="outer">
<div id="inner">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed id velit vel augue fringilla rhoncus at et odio. Suspendisse potenti. Aliquam justo libero, commodo ut iaculis in, placerat vel purus.
</div>
</div>
</div>