Mã này (demo) cho phép bất kỳ width
và height
được thiết lập, mà không cần phải cập nhật bất kỳ thuộc tính khác (ví dụ top
= height/2
) hoặc dựa vào kỹ thuật mà aren' t cũng hỗ trợ (ví dụ display:table;
một nhược điểm là hỗ trợ cho các phiên bản IE cũ thiếu Kết hợp điều này với một giải pháp cho IE chỉ có thể là bạn đang đặt cược tốt nhất
CSS:...
.absoluteCenter {
/* Must manually set width/height */
width:800px;
height:500px;
/* The magic centering code */
margin:auto;
position:absolute;
top:0;bottom:0; /* Aligns Vertically - Remove for Horizontal Only */
left:0;right:0; /* Aligns Horizontally - Remove for Vertical Only */
/* Prevent div from overflowing main window */
max-width:100%;
max-height:100%;
overflow:auto;
}
/* IE 7 and Below */
:first-child+html .absoluteCenter,
* html .absoluteCenter {
/* Place code here to override all above values, and add IE friendly centering */
}
Và HTML:
<div class="absoluteCenter">
Content of DIV
</div>
Bạn có cần hỗ trợ ie7 không? – mrtsherman
Im không phải là siêu lo lắng về hỗ trợ ie7, mặc dù ie8 sẽ tốt đẹp. –