Example of the center of a CSS floating element

Source: Internet
Author: User


The center of floating elements is not often used, but in order to cope with some wonderful interviewers, you also need to know how to solve the problem.

Post a piece of CSS code:

width:50%; height:300px; Float:left;  margin-left:50%; position:relative; Left:-25%;background-color: #ccc;

The key is to give a left margin, and then locate, so that leave value is half of the div width, you can achieve.

In fact, this method is also to do the window, so that it is located in the middle of the browser is commonly used methods: to a left (up) margin, in the position to the top value.

Example


<style type= "Text/css" >
. Divs{background: #ccc; width:600px;height:300px;margin:50px auto 0;}
. divs div{margin:0 Auto;background: #000; width:400px;text-align:center;}
P{float:left;height:100px;width:98px;background: #fff; border:1px solid red;margin:0 Auto;}
</style>
<body>
<div class= "DIVs" >
<div>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<p>p4</p>
</div>
</div>
</body>

We found that the center effect is also achieved, but its scalability is poor, if you delete a P or add a p, you need to the. DIVs Div This style of width to modify

Related Article

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.