CSS弹性布局,需要一个容器,容器中至少包含一个以上的元素,以下代码包含子元素垂直居中、水平居中、居中三种情况

<html>
<head>
<style type="text/css">
div {
  height: 200px;
  width:200px;
  background-color: blue;
  color: white;
  margin: 10px;
}

div > p:first-child {
   background-color: green;
}
div > p:last-child {
   background-color: red;
}
div > p {
 padding: 5px;
 margin:5px;
 width: fit-content;
}

.flex-middle {
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex-middle {
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex-middle {
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex-middle {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column; /* 子元素垂直分布 */
}
.flex-horizontal-middle {
  display: flex;
  align-items: center;
  flex-direction: column;
}
.flex-vertical-middle {
  display: flex;
  justify-content: center;
  flex-direction: column;  /* 子元素垂直分布 */
}

.flex-horizontal {
  display: flex;
}
.flex-horizontal > p {
 	flex: 1;
    height:fit-content;
    justify-content:space-around;
    margin: 0 2px 0 2px;
}
.flex-horizontal > p:first-child {
	margin-left: 0px;
    margin-right: 2px;
}
.flex-horizontal > p:last-child {
    margin-right: 0px;
    margin-left: 2px;
}

.div0 {
	background: green;
	width: 820px;
    height: fit-content;
    padding: 10px;
	display:flex; 
    flex-flow: wrap; /* 容器中的子元素会自动换行,从左往右均匀排列 */
    align-content: flex-start; /* 子元素在容器顶部排列,会解决换行时子元素行间距变大的原因*/
}

.div-1{
 	width: calc(25% - 22px);
    background: blue;
    color: white;
    padding: 10px;
    border: 2px solid red;
    height:100px;
    margin-left: 0px;
    margin-bottom: 0px;
    margin-top: -2px;
    margin-right: -2px;
}

</style>
</head>

<body>
	<p>垂直居中:</p>
	<div class="flex-vertical-middle"> 
    	<p>内容垂直居中1</p>
        <p>内容垂直居中2</p>
    </div>
    <p>水平居中:</p>
    <div class="flex-horizontal-middle"> 
    	<p>内容水平居中1</p>
        <p>内容水平居中2</p>
    </div>
    <p>居中:</p>
    <div class="flex-middle"> 
    	<p>内容居中1</p>
        <p>内容居中2</p>
    </div>
    
    <p>水平平均分布:<p/>
    <div class="flex-horizontal"> 
    	<p>内容1</p>
        <p>内容2</p>
        <p>内容3</p>
        <p>内容4</p>
    </div>
	<p>flex自动换行,相邻子元素border去重叠<p/>
	<div class='div0'>
      <div class="div-1">A</div>
      <div class="div-1">B</div>
      <div class="div-1">C</div>
      <div class="div-1">D</div>
      <div class="div-1">E</div>
      <div class="div-1">F</div>
      <div class="div-1">G</div>
      <div class="div-1">H</div>
      <div class="div-1">I</div>
    </div>
</bo![在这里插入图片描述](https://img-blog.csdnimg.cn/e24019fd9ca04aba8e99a89b309d32e1.png#pic_center)
dy>

</html>

代码运行结果:
在这里插入代码片在这里插入图片描述
在这里插入图片描述

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐