Horizontal vertically centered method for three absolutely positioned elements in CSS

Source: Internet
Author: User

1.CSS Achieve Center

Disadvantage: You need to know the width and height of the element in advance.

<!doctype html>
<metacharset= "UTF-8" >
<title>Document</title>
<style>
. box{
width:600px;
height:400px;
Position:absolute;
left:50%; top:50%;
border:1px solid #000;
background:red;
Margin-top: -200px; /* Height of half * *
Margin-left: -300px; /* Width of half * *
}
</style>
<body>
<divclass= "box" >
</div>
</body>

2, CSS3 to achieve horizontal vertical center

Note: The element can be centered, regardless of its size. However, IE8 above is compatible with this type of writing, mobile end can be ignored.

<!doctype html>
<metacharset= "UTF-8" >
<title>Document</title>
<style>
. box{
width:600px;
height:400px;
Position:absolute;
left:50%;
top:50%;
border:1px solid #000;
background:red;
Transform:translate (-50%,-50%); /* 50% is half of its own size * *
}
</style>
<body>
<divclass= "box" >
</div>
</body>

3, Margin:auto Implementation Center

<!doctype html>
<metacharset= "UTF-8" >
<title>Document</title>
<style>
. box{
width:600px;
height:400px;
Position:absolute;
left:0;
top:0;
right:0;
bottom:0;
border:1px solid #000;
background:red;
Margin:auto; * * With this will automatically center.
}
</style>
<body>
<divclass= "box" >
</div>
</body>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.