子元素相对父元素垂直水平居中的八种方式

基本样式

HTML


<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Documenttitle>
    <link rel="stylesheet" href="./style.css" />
  head>
  <body>
    <div id="out">
      <div id="inner">div>
    div>
  body>
html>

CSS

#out {
  width: 300px;
  height: 300px;
  background-color: red;
}
#inner {
  width: 50px;
  height: 50px;
  background-color: blue;
 }

方式一:flex

#out {
  display: flex;
  justify-content: center;
  align-items: center; 
} 

方式二:flex(父)+margin(子)

#out{
	display:flex;
}
#inner{
	margin:auto;
}

方式三:position + calc

#out {
  position: relative;
}
#inner {
  position: absolute;
  left: calc(50% - 25px);
  top: calc(50% - 25px);
}

方式四:position + margin

#out {
  position: relative;
  border: 1px solid red;/*防止垂直方向margin重叠*/
}
#inner {
  margin-left: calc(50% - 25px);
  margin-top: calc(50% - 25px);
}  

方式五:position + margin(2)

#out {
  position: relative;
}
#inner {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -25px;
  margin-left: -25px;
}  

方式六:position + margin(3)

#out {
  position: relative;
}
#inner {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  position: absolute;
  margin: auto;
}

方式七:position + transform

#out {
  position: relative;
}
#inner {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

方式八:lineheight(父) + display:inline-block(子)

#out {
  line-height: 325px;
  vertical-align: center;
  text-align: center;
}
#inner {
  display: inline-block;
}

你可能感兴趣的:(CSS)