Inline elements

<div class="demo1">1111</div
Copy the code
.demo1 {
  width: 100px;
  height: 30px;
  border: 1px solid #333;
}
Copy the code

line-height + text-align

.demo1 {/* align = center */ text-align: center; /* height = height */ height: 30px; }Copy the code

Block elements in the line

line-height + vertical-align + text-align

Vertical-align can only be applied to inline elements and cell elements.

<div class="demo1"> <img SRC = "https://dss2.bdstatic.com/6Ot1bjeh1BF3odCf/it/u=1765461753, & app = 92 & 2420530801 & FM = 218 f = PNG? W = 121 & 75 & h = s = A7D53F6EC4F0 7F803ADE5F7D0300D07C"> </div>Copy the code
.demo1 { width: 500px; height: 200px; border: 1px solid #333; /* text-align: center; line-height: 200px; } img { vertical-align: middle; }Copy the code

display: table/table-cell + vertical-align + text-align

<div class="demo1">
  <div class="content">
    <p>1111111</p>
    <p>2222222</p>
  </div>
</div>
Copy the code
.demo1 { width: 500px; height: 200px; border: 1px solid #333; /* display: table; } .content { vertical-align: middle; display: table-cell; text-align: center; }Copy the code

Block elements

<div class="parent">
    <div class="child"></div>
</div>
Copy the code

position + margin

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}
Copy the code

flex + margin

.parent { display: flex; /* Define how items are aligned on the main axis */ justify-content: center; /* Define how items are aligned on the cross axis */ align-items: center; }Copy the code

or

.parent {
  display:flex;
}
.child {
  margin: auto;
}
Copy the code

grid

.parent {
    display: grid;
}
.child {
    justify-self: center;
    align-self: center;
}
Copy the code

or

.parent {
    display:grid;
}
.child {
    margin: auto;
}
Copy the code