[英]Make a DIV vertically align in a middle
我必須制作類似列的內容,但沒有表格。 這是示例代碼:
<div class="main">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
<div class="endfloat"></div>
</div>
.left
位於左側, .center
位於中間,而.right
應該位於右側。 但是, .center
也應該垂直對齊中間。 這是示例和CSS示例: jsFiddle
包裝實際元素是一個表格單元:
的HTML
<div class="main">
<div class="table-cell">
<div class="left"></div>
</div>
<div class="table-cell">
<div class="center"></div>
</div>
<div class="table-cell">
<div class="right"></div>
</div>
</div>
SCSS
@mixin defaultDiv($bg, $height: 300px) {
width: 200px;
height: $height;
background-color: $bg;
display: table-cell;
}
.main {
outline: 1px solid red;
width: 600px;
display: table;
.table-cell {
display: table-cell;
width: 200px;
vertical-align: middle;
}
.left {
@include defaultDiv(green);
}
.center {
@include defaultDiv(blue, 200px);
}
.right {
@include defaultDiv(yellow, 250px);
}
}
JSFiddle演示: http : //jsfiddle.net/3728vxa9/2/
根據中心元素的高度是像素還是百分比,可以在其頂部和下方放置一個div。 例如,如果高度為50%,則在其上方和下方放置一個div,每個div的高度為25%。
HTML將如下所示
<div class="main">
<div class="left"></div>
<div class="centerTop"></div>
<div class="center"></div>
<div class="centerBottom"></div>
<div class="right"></div>
<div class="endfloat"></div>
</div>
CSS將如下所示
.centerTop {
height: 25%
}
.center {
height: 50%
}
.centerBottom {
height: 25%
}
以下是兩個可以在中間對齊div的方法的示例:
使用HTML:
<div class="center" style="margin: 0 auto;"></div>
在單獨的CSS文件中進行樣式設置:
.center { margin: 0 auto; }
如果要制作三列,並希望它們根據窗口寬度調整大小,則將其寬度的值設置為33%。 這是一個例子:
.center {
width: 33%;
}
.left {
width: 33%;
}
.right {
width: 33%;
}
請參閱此鏈接, http://jsfiddle.net/n6t3qrux/
@mixin defaultDiv($bg, $height: 300px) {
float: left;
width: 200px;
height: 300px;
background-color: $bg;
}
.main {
outline: 1px solid red;
width: 600px;
height: 300px;
position: relative;
.left {
@include defaultDiv(green);
margin: auto;
position: absolute;
left: 0;
top: 0;
}
.center {
@include defaultDiv(blue, 200px);
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
height: 200px;
}
.right {
@include defaultDiv(yellow, 250px);
margin: auto;
position: absolute;
right: 0;
top: 0;
}
.endfloat {
clear: both;
}
}
希望對您有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.