Three ways to center the DIV block horizontally vertically in HTML

Source: Internet
Author: User

First scenario: The case of a DIV block inside the box

div.myid{display:flex;justify-content:center;align-items:center;height:500px;} Div.myid div.mydiv{width:200px;height:200px;border:1px solid Red;}

Low-version browser compatibility is not good enough, choose to be cautious,

The second option: to center the Div in the box, using the positioning method;

Div.myid{height:500px;position:relative;} Div.myid div.mydiv{width:200px;height:200px;border:1px Solid red;position:absolute;left:50%;top:50%;margin-left:- 100px;margin-top:-100px;}

  

The third method of using positioning: using the upper and lower left to 0, and then Margin:auto; Absolute Center

div.myid{width:500px;height:500px;position:relative;border:1px solid #333;} Div.myid Div.kg{}div.myid div.mydiv{width:200px;height:200px;border:1px Solid red;line-height:40px;position: Absolute;left:0;top:0;bottom:0;right:0;margin:auto;}

The last option is to use the parent element display:table; child element: Display:table-cell;vertical-align:middle; This method I do not like, so first do not collect, to use when Baidu comes out a lot;

By the way, the absolute center of the text element is used: line-height:40px; (high of the parent element) Text-align:center;

Three ways to center the DIV block horizontally vertically in HTML

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.