The method of horizontal centering of three kinds of indefinite wide block elements

Source: Internet
Author: User

In general, it is relatively simple to horizontally center a fixed-width block element, and we only need to set the width of the block element and set margin:0 Auto. However, for block elements that cannot be set to a fixed width, this trick does not work.

Let me introduce the three commonly used methods to set the horizontal center of an indefinite wide block element.

First: horizontal centering with float+relative

CSS code:

. Wrap { float: left; position: relative; Left:50%;  border: 1px solid red;    } . Content{ position: relative;  left: -50%;  border:1px solid Blue; }

HTML code

    <class= "wrap">        <class= " Content "> What needs to be centered </div>    </  div>

Second: Horizontal centering using table

CSS Code

    . Wrap{        margin:0 auto;         Border: 1px solid red;    }     . Content{        border: 1px solid blue;    }

HTML code

    <Tableclass= "Wrap">        <TR>            <TD>                <Divclass= "Content">Content that needs to be centered</Div>            </TD>        </TR>    </Table>

  

  

Third: Use Display:inline to achieve horizontal centering (Inline-block effect is the same)

CSS Code

    . Wrap{        text-align: center;         Border: 1px solid red;    }     . Content{        display: inline;/*inline-block can also */        border : 1px solid blue;    }

HTML code

<class= "wrap">        <class= " Content "> What needs to be centered </div>        </Div  >

The method of horizontal centering of three kinds of indefinite wide block elements

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.