你可以用下面的代碼實現這一點:
HTML:
<div id="wrapper">
<div id="container">
<div id="variable">test</div>
<div id="fixed">test</div>
</div>
</div>
CSS:
#wrapper { overflow: hidden; }
#container {
float: left;
position: relative;
left: 50%; }
#container > div {
float: left;
position: relative;
right: 50%;
height: 300px; }
#variable {
background: red;
width: 300px; }
#fixed {
background: blue;
width: 200px; }
前瞻:http://jsfiddle.net/Wexcode/mreLt/
您還可以通過包裝達到這種效果一個容器中的兩個元素,將它們設置爲display: inline-block
,最後將其容器設置爲text-align: center
。
答案比這個稍微複雜一些,所以讓我知道你是否想選擇這條路線。
爲了使它不會落入下一行,請使用inline-block
。
<div id="container">
<div id="variable">
<p>test</p>
</div><div id="fixed">
<p>test</p>
</div>
</div>
CSS:
body { margin: 0; }
#container {
color: #fff;
text-align: center;
white-space: nowrap; }
#container > div {
height: 300px;
display: inline-block; }
#variable {
background: red;
width: 100px; }
#fixed {
background: blue;
width: 200px; }
預覽:http://jsfiddle.net/Wexcode/mreLt/2/
來源
2012-01-09 08:41:27
Wex
OP具體說容器寬度是未知的。 – Wex 2012-01-09 08:36:06
我決定不添加容器div並使用javascript就無法做到。它實際上工作正常,但我有點擔心跨瀏覽器compat和頁面加載「閃光燈」。 – Darthg8r 2012-01-09 13:57:58