標籤:enter justify cal 頁面 bsp 彈性布局 ems window 左移
一、如何讓一個div在頁面中垂直置中(請至少列出三種)
1.距離頁面視窗左邊框和上邊框的距離設定為50%,這個50%就是指頁面視窗的寬度和高度的50%,最後將該DIV分別左移和上移,左移和上移的大小就是該DIV寬度和高度的一半。
width:300px;
height:200px;
position:absolute;
left:50%
top:50%;
margin:-100px 0 0 -150px ;
2.使用jquery代碼
$(window).resize(function(){
$(".mydiv").css({
position: "absolute",
left: ($(window).width() - $(".div").outerWidth())/2,
top: ($(window).height() - $(".div").outerHeight())/2
});
});
3.使用絕對位置;top,bottom,left,right分別都為零
父元素設定為:
width:800px;
height:500px;
border:2px solid #000;
position:relative;
子項目設定為:
width:200px;
height:200px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
4.(此方法暫時只能設定元素在父級元素中垂直置中,還沒有實現水平置中),使用display:table-cell
父元素設定為:
width:800px;
height:500px;
border:2px solid #000;
display:table-cell;
vertical-align:middle;
text-align: center;
子項目設定為:
width:200px;
height:200px;
display:inline-block;
5.實用彈性布局的方式來解決
父級元素設定為
width:800px;
height:500px;
border:2px solid #000;
display:flex;
justify-content:center;
align-items:center;
子項目設定為:
width: 200px;
height: 200px;
background-color: red;
利用css來讓一個div在頁面中垂直置中的方法