How CSS allows floating elements to be centered horizontally

Source: Internet
Author: User

For fixed-width non-floating elements we can be horizontally centered in CSS with margin:0 auto, and we have a common technique to solve the problem of horizontal centering for variable-width floating elements. To solve the problem of horizontal centering there are many ways, the following first to share a few three ways, I hope to help everyone.

Method One:

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%;}

So it seems simple, the parent and child elements are floating at the same time, then the parent element moves relative to the left by 50%, then the child element moves relative to the right 50%, or the child element moves relative to the left-50%. So simple and so magical.

Method Two:

HTML Code

<! DOCTYPE html>

The parent and child elements are left floating at the same time, then the parent element moves relative to the left by 50%, and then the child element moves relative to the left-50%.

Method Three:

HTML code

<! DOCTYPE html>

Here can also set a layer of left:-50%, more reasonable, also can avoid some unnecessary ie BUG. Extrapolate, the way the float element is centered can actually be extended to many situations where floating elements need to be centered.

There are three ways to teach CSS how to center a floating element horizontally

How CSS allows floating elements to be centered horizontally

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.