CSS基础5-垂直居中与图片处理,前端知识总结
    		       		warning:
    		            这篇文章距离上次修改已过448天,其中的内容可能已经有所变动。
    		        
        		                
                
/* 使用Flexbox实现垂直居中 */
.container {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
}
 
/* 使用Grid实现垂直居中 */
.container {
  display: grid;
  place-items: center; /* 水平垂直同时居中 */
}
 
/* 使用定位方法实现垂直居中 */
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
 
/* 使用伪元素和负margin实现垂直居中 */
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto;
  height: 50px; /* 需要指定高度 */
}
 
/* 使用line-height实现单行文本垂直居中 */
.container {
  height: 100px;
  line-height: 100px; /* 等于容器高度 */
}
 
/* 使用图片处理技术实现图片的响应式居中和自适应宽度 */
.img-container {
  position: relative;
  width: 100%; /* 宽度占满容器 */
  height: 300px; /* 设置固定高度 */
  overflow: hidden; /* 超出部分隐藏 */
}
.img-container img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 使图片居中 */
  max-width: 100%; /* 图片宽度不超过容器宽度 */
  height: auto; /* 高度自动缩放 */
}以上代码示例展示了如何使用不同的CSS技术实现容器内的内容(包括文本、图片等)的垂直居中,并对图片进行了响应式处理,确保在容器大小变化时图片仍然可以正确居中显示。
评论已关闭