How does css align floating elements horizontally and css floating elements horizontally?

Source: Internet
Author: User

How does css align floating elements horizontally and css floating elements horizontally?

For non-floating elements with a fixed width, we can use margin: 0 auto in CSS to center horizontally. For floating elements with an indefinite width, we also have a common technique to solve its horizontal center problem. There are many ways to solve the problem of horizontal center. I would like to share with you three methods to help you.

Method 1:

1. HTML part:

<Div class = "box"> <p> I am floating </p> <p> I am also centered </p> </div>

2. CSS part:

.box{ float:left; position:relative; left:50%;}p{ float:left; position:relative; right:50%;}

In this case, it is easy. The parent element and the child element float left at the same time, then the parent element moves 50% to the left, and the child element moves 50% to the right, or move the child element to the left to 50%. It's so simple and amazing.

Method 2:

HTML code

<! DOCTYPE html> 

The Parent and Child elements float left at the same time, then the parent element moves 50% to the left, and then the child element moves-50% to the left.

Method 3:

Html code

<! DOCTYPE html> 

Here we can also set left:-50% in multiple layers, which is more reasonable and can avoid unnecessary IE bugs. In contrast, this float element center method can be applied to many situations where floating elements need to be centered.

The above three methods explain how css centralizes floating elements horizontally. In the future, this website will continue to update programming knowledge such as js, jq, css, php, and c, please pay attention to this site. Thank you.

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.