如果支持旧的浏览器是不是一个大问题,您可以使用css's calc()
Working Example
html, body {
height:100%;
width:100%;
}
#pageWrapper {
width:100%;
height:100%;
}
#top {
width:200px;
height:calc(100%/3 - 10px);
background: red;
}
#middle {
width:200px;
height:calc(100%/3 - 10px);
background: blue;
margin-top: 15px;
margin-bottom: 15px;
}
#bottom {
width:200px;
height:calc(100%/3 - 10px);
background: green;
}
p {
position:relative;
top:calc(50% - 10px);
}
如果您需要支持旧的浏览器,你不介意Rube Goldberg方法你可以使用jQu红霉素:
Working Example
var rubeGoldberg = function() {
$('#top, #middle, #bottom').height($('body').height()/3 - $('body').height() * 0.02);
$('#middle').css({
marginTop: $(document).height() * 0.03,
marginBottom: $(document).height() * 0.03
});
$('p').each(function() {
$(this).css({
top: $(this).parent().height()/2 - $(this).height()/2
});
});
};
$(function() {
rubeGoldberg();
});
$(window).resize(function() {
rubeGoldberg();
});
或者,如果jQuery是不是真的是你的味道,这里的大致相同鲁贝戈德堡的做法是Vanilla JS
Working Example
function rubeGoldberge() {
var secElems = document.getElementsByClassName('sec');
var mid = document.getElementById('middle');
var paraElems = document.getElementsByTagName('p');
for (var i = 0; i < secElems.length; i++) {
secElems[i].style.height = window.innerHeight/3 - window.innerHeight * 0.02 + 'px';
mid.style.margin = window.innerHeight * 0.03 + 'px 0px';
paraElems[i].style.top = (paraElems[i].parentNode.clientHeight/2) - paraElems[i].clientHeight/2 + 'px';
}
mid.style.margin = window.innerHeight * 0.03 + 'px 0px';
}
window.onload = rubeGoldberge();
window.addEventListener('resize', rubeGoldberge);
如果我想垂直对齐中间div ent中心我会使用vertical-align:middle? – nick
不幸的是没有。但是你可以在你的'#middle' div中加入另一个div,例如'#middleInner'并将此样式添加到它:'vertical-align:middle; display:table-cell;'。在我更新的[FIDDLE](http://jsfiddle.net/vCL6G/2/) – matewka
很酷的谢谢你看。 – nick