2013-12-19 33 views
0

我想創建一個在頁面上水平居中的div。在div的左邊,我想要與div相同的背景色。在右邊,我想要與背景相同的顏色。我的問題是,隨着窗口變大,div的大小增長得比它應該更快,直到div的另一端。我怎樣才能解決這個問題?居中div與每邊不同顏色的邊距

我試過以下。

<div id="holder"> 
    <div id="text"> 
    Text goes here 
    </div> 
</div> 

我的CSS:

#holder{ 
background:#3B92C0; 
position:relative; 
min-width:1090px; 
left:-200px; 

} 
#text{ 
position:relative; 
width:1090px; 
border:0 auto; 
left:200px; 
} 

這裏是fiddle

回答

1

檢查這項小提琴:http://jsfiddle.net/vvqZj/

的想法是給包含文本的-1000px左邊距和1000px左填充的div,所以背景將於1000像素左邊的文字開始的地方。

這種方法的不足之處是你需要圍繞以文本爲中心的文本的另一個包裝。這是因爲您不能將margin: auto設置爲包含文本的div,因爲您會覆蓋此div的左邊距。

0

請檢查http://jsfiddle.net/raunakkathuria/qhFaD/3/

變化

#holder{ 
background:#3B92C0; 
position:relative; 
margin:0 auto; 

} 
#text{ 
position:relative; 
width:500px; 
background:#555; 
text-align:left; 
margin:0 auto; 
color:#fff; 
} 
0

沒有尾巴!

http://jsfiddle.net/t2SYv/

<div id="regular">THis is a regular centerd div</div> 
<div id="holder"> 
     <div id="text"> 
     This looks good when window is small but when it grows it gets a tail<br> 
      How do i get rid of this tail when window is big ---------------&gt; 
     </div> 
     <div id="filler"></div> 
</div> 

CSS:

#regular 
{ 
    background:#ccc; 
    height:200px; 
    margin:0 auto 10px; 
    width:500px; 
} 

#holder 
{ 
    background:#3B92C0; 
    margin:0 auto; 
    min-width:500px; 
    position:relative; 
    text-align:center; 
} 

#text 
{ 
    background:#555; 
    color:#fff; 
    display:inline-block; 
    margin:0 auto; 
    position:relative; 
    text-align:left; 
    width:500px; 
    z-index:2; 
} 

#filler 
{ 
    background:#FFF; 
    display:inline-block; 
    height:100%; 
    position:absolute; 
    right:0; 
    width:50%; 
    z-index:1; 
}