Edited: 2018-05-13

I. For inline elements:

text-align:center;
Copy the code

For block-level elements with specified width:

  1. Margin and width are horizontally centered

Margin-left :auto; margin-left:auto; margin-right:auto;

  1. Absolute positioning and margin-left: -(width value /2) horizontal center

Fixed-width block-level elements are horizontally centered by using absolute positioning, and by setting the element margin-left to half its width

.content{ width: 200px; position: absolute; left: 50%; margin-left: -100px; // Half the width of the element, 100px background-color: aqua; }Copy the code
  1. Position: Absolute + (left=0+top=0+right=0+bottom=0) + margin:auto
.content{

  position: absolute;

  width: 200px;

  top: 0;

  right: 0;

  bottom: 0;

  left: 0;

  margin: auto;

}
Copy the code

3. For block-level elements of unknown width:

  1. The table tag is horizontally centered with margin left and right Auto

Use the table tag (or simply set the block-level element to display:table) and add a margin of auto to the tag

  1. Inline-block implements a horizontally centered method

Display: inline – block; (display:inline) and text-align:center; Achieve horizontal center

Problem: Browser compatibility for inline-block needs additional handling (white space for inline-block elements)

  1. Absolute positioning achieves horizontal centering

Absolute positioning + Transform, translateX can move 50% of local elements

.content{

  position: absolute;

  left: 50%;

  transform: translateX(50%);/* Move the element itself by 50% */

  background: aqua;

}
Copy the code
  1. Relative positioning to achieve horizontal center

Use float or display to change the parent element to an inline block element

.contentParent{

  display: inline-block; /* Convert the parent element to an inline block element */

  /*float: left; Convert the parent element to an inline block element */

  position: relative;

  left: 50%;

}

/* Target element */

.content{

  position: relative;

  right: 50%;

  background-color:aqua;

}
Copy the code
  1. CSS3 flex implements the horizontal centering method, Method one
.contentParent{

  display: flex;

  flex-direction: column;

}

.content{

  align-self:center;

}
Copy the code
  1. CSS3 flex implements the horizontal centering method, Method two
.contentParent{

  display: flex;

}

.content{

  margin: auto;

}
Copy the code
  1. CSS3 fit-content with left and right margin for auto to achieve horizontal center method
.content{

  width: fit-content;

  margin-left: auto;

  margin-right: auto;

}
Copy the code

Reference article:

  • www.w3cplus.com/css/element…
  • Blog.sina.com.cn/s/blog_c112…