2016-10-25 73 views
0

我愿做如下 -分割一个div分成四个格

------------------------------------ 
| ------------- ------------- | 
| |  1  |  2  | | 
| |   |   | | 
| ------------- ------------- | 
| |  3  |  4  | | 
| |   |   | | 
| --------------------------- | 
------------------------------------ 

到目前为止,我tried-

body, 
 
html { 
 
    padding: 0; 
 
    margin: 0; 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 
#top { 
 
    width: 100%; 
 
    background-color: red; 
 
    height: 15%; 
 
} 
 
#bottom { 
 
    width: 100%; 
 
    background-color: blue; 
 
    height: 85%; 
 
} 
 
.inner { 
 
    width: 49%; 
 
    height: 49%; 
 
    border: 1px solid black; 
 
    float: left; 
 
}
<div id="top"></div> 
 
<div id="bottom"> 
 
    <div class="inner">1</div> 
 
    <div class="inner">2</div> 
 
    <div class="inner">3</div> 
 
    <div class="inner">4</div> 
 
</div>

但所有inner的div是左对齐。如何在bottom div内水平对齐中心?

+0

我不完全明白你的问题,但现在我感觉有些Flexbox的闻到这里;) – Stratboy

+0

你能解释一下水平居中的意思吗? –

+0

这里是小提琴这个:https://jsfiddle.net/nj6qfgxn/ – peszo

回答

2

使用box-sizing: border-box;并且您可以使用50%,因为边框以百分比计算。

body, 
 
html { 
 
    padding: 0; 
 
    margin: 0; 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 
#top { 
 
    width: 100%; 
 
    background-color: red; 
 
    height: 15%; 
 
} 
 
#bottom { 
 
    width: 100%; 
 
    background-color: blue; 
 
    height: 85%; 
 
} 
 
.inner { 
 
    width: 50%; 
 
    height: 50%; 
 
    box-sizing: border-box; 
 
    border: 1px solid black; 
 
    float: left; 
 
    text-align: center; 
 
    padding: 16px; 
 
}
<div id="top"></div> 
 
<div id="bottom"> 
 
    <div class="inner">1</div> 
 
    <div class="inner">2</div> 
 
    <div class="inner">3</div> 
 
    <div class="inner">4</div> 
 
</div>

+0

谢谢。它正在工作。 +1。 –

+0

有一件事,如果我想绝对中心内部div的内容? –

+0

如果你想中心div的内容使用这个------------ ---------------- .inner { width:50%; 身高:50%; box-sizing:border-box; 边框:1px纯黑色; display:inline-block; text-align:center; } –

0

的Flexbox的方式:

https://jsfiddle.net/hfxx1awp/4/

#top{ 
    background-color:red; 
    height:15%; 
} 

#bottom{ 
    display: flex; 
    flex-wrap:wrap; 
    height:85%; 
    background-color:blue; 
} 

#bottom > *{ 
    flex-basis: auto; 
    width:50%; 
    box-sizing:border-box; 
    border:1px solid black;  
} 

这里还有一个更先进的方式,SCSS和排水沟。很明显,你可以进一步完善其添加为最后一行零保证金,也使一个混合出来的:

https://jsfiddle.net/hfxx1awp/5/

#bottom > *{ 
    $columns: 2; 
    $gutter_width: 15px; 
    $gutters: $columns - 1; 
    $gutter_offset: $gutter_width * $gutters/$columns; 
    width: calc(50% - #{$gutter_offset}); 
    flex-basis: auto; 
    box-sizing:border-box; 
    border:1px solid black; 

    &:nth-child(#{$columns}n){ 
    margin-right: 0; 
    } 

    // apply margin 
    @for $i from 0 through ($gutters){ 
    @if($i != 0){ 
     &:nth-child(#{$columns}n+#{$i}){ 
     margin-right: $gutter_width; 
     } 
    } 
    } 

    margin-bottom: $gutter_width; 
}