2016-01-07 50 views
0

我有一个header,和两个div元素。外部div垂直居中在我的header元素中。我想要内部div伸展到100%的宽度。我该怎么做呢?如何让内部div伸展至100%宽度?

查看this fiddle仅供参考。我希望蓝色部分占据整个宽度的100%。

下面的代码藏汉:

HTML:

<header id="header-index"> 
    <div id="header-index-inner"> 
     <div id="inner-div"> 

       <h1>Header</h1>    
       <h5>Subheader1 </h5> 
       <h5>Subheader2 </h5> 

     </div> 
    </div> 
</header> 

CSS:

#header-index{  
    background-color: red; 
} 

#header-index-inner{ 
    width: 100%; 
    display: table-cell; 
    vertical-align: middle; 
    height: 400px; 
} 

#inner-div{ 
    background-color:blue; 
    width:100%; 
} 
+2

[为什么宽度:100%无法在div {display:table-cell}上工作?](http://stackoverflow.com/questions/17736570/why-is-width-100-not-working -on-DIV-显示表单元) – Sam

回答

1

的问题是#header-index-innerdisplay: table-cell没有伸展100%。

父需要分配display: table,以及宽度100%:

#header-index {  
    background-color: red; 
    display: table; 
    width: 100%; 
} 

#header-index-inner { 
    width: 100%; 
    display: table-cell; 
    vertical-align: middle; 
    height: 400px; 
} 

#inner-div{ 
    background-color:blue; 
    width:100%; 
} 

Updated Fiddle

1

添加以下的#标题索引规则:

display:table; 
width:100%; 
1

代替改变使用表格和表格单元的显示的,可以使用定位居中内分度:

#header-index { 
 
    background-color: red; 
 
} 
 
#header-index-inner { 
 
    width: 100%; 
 
    height: 400px; 
 
} 
 
#inner-div { 
 
    background-color: blue; 
 
    top: 50%; 
 
    position: relative; 
 
    transform: translate(0%, -50%); 
 
}
<header id="header-index"> 
 
    <div id="header-index-inner"> 
 
    <div id="inner-div"> 
 
     <h1>Header</h1> 
 
     <h5>Subheader1 </h5> 
 
     <h5>Subheader2 </h5> 
 
    </div> 
 
    </div> 
 
</header>