CSS水平垂直居中(最常见的三种方案flex、grid、absolute)
    		       		warning:
    		            这篇文章距离上次修改已过439天,其中的内容可能已经有所变动。
    		        
        		                
                
/* 解决方案1:使用flex布局 */
.parent-flex {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}
 
/* 解决方案2:使用grid布局 */
.parent-grid {
  display: grid;
  place-items: center; /* 水平垂直同时居中 */
}
 
/* 解决方案3:使用绝对定位 */
.parent-absolute {
  position: relative;
}
.child-absolute {
  position: absolute;
  top: 50%; /* 向下偏移50% */
  left: 50%; /* 向右偏移50% */
  transform: translate(-50%, -50%); /* 向左和向上各偏移50%,实现居中 */
}
 
/* HTML结构 */
<div class="parent-flex">
  <div>水平垂直居中内容</div>
</div>
 
<div class="parent-grid">
  <div>水平垂直居中内容</div>
</div>
 
<div class="parent-absolute">
  <div class="child-absolute">水平垂直居中内容</div>
</div>这段代码提供了三种不同的方法来实现水平和垂直居中,分别使用了flex布局、grid布局和绝对定位。每种方法都有相应的HTML结构作为示例。
评论已关闭