Canh giữa thành phần – resize

Trở về

  • 2,912

Canh thành phần giữa màn hình ngay cả khi resize màn hình lớn nhỏ khác nhau.

Thành phần canh giữa window theo chiều dọc và ngang

Canh giữa thành phần window theo chiều dọc và ngang, cho dù có resize window hay không.

Html viết:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Học Web Chuẩn</title>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$(window).bind("load resize",function(){
    var win = $(window);
    var box = $(".box");
    var top = ( win.height() - box.height() ) / 2;
    var left = ( win.width() - box.width() ) / 2;
    box.css({"position": "absolute",
              "top": top,
              "left": left});
});
</script>
<style>
* { /* reset lại margin và padding cho các tag */
    margin: 0;
    padding: 0;
}
.box {
    border: 1px solid #c00;
    height: 200px;
    width: 200px;
}
</style>
</head>
<body>
<div class="box">text</div>
</body>
</html>

Click để xem kết quả

Download file để thực hành

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.