css中的各种居中方法

CSS盒子居中对齐技巧

在网页布局中,元素的居中对齐是最常见也最重要的布局需求之一。本文将介绍CSS中各种盒子居中对齐的技巧,包括水平居中、垂直居中以及水平垂直同时居中的多种实现方法。

一、水平居中

1. 行内元素水平居中

对于行内元素(如文本、span等),可以使用text-align: center

.parent {
  text-align: center;
}

2. 块级元素水平居中

对于块级元素(如div),设置margin: 0 auto

.child {
  width: 200px; /* 必须指定宽度 */
  margin: 0 auto;
}

3. Flexbox实现水平居中

.parent {
  display: flex;
  justify-content: center;
}

4. Grid实现水平居中

.parent {
  display: grid;
  justify-content: center;
}

二、垂直居中

1. 单行文本垂直居中

.parent {
  height: 100px;
  line-height: 100px; 
}

2. 使用padding实现简单垂直居中

.parent {
  padding: 20px 0;
}

3. 绝对定位实现垂直居中

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

三、水平垂直同时居中

1. 有定位的一些情况

html结构
<div class="parent">
        <div class="child"></div>
    </div>
基础结构
.parent {
 	position: relative;
    height: 200px;
    background-color: red;
 }
.child {
   width: 100px;
   height: 100px;
   position: absolute;
   background-color: blue;
}

下述方式都是需要添加的样式

1. 绝对定位+margin

.child {
	left: 50%;
	top: 50%;
	margin-top: -50px;
    margin-left: -50px;
}

2. 绝对定位+calc

.child {
	left: calc(50% - 50px);
	top: calc(50% - 50px);     
}

3. 绝对定位+transform

.child {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

4. 绝对定位+margin auto

.child {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 200px; /* 需要指定宽高 */
  height: 100px;
}

2. 没有定位的情况

html结构
<div class="parent">
        <div class="child"></div>
    </div>

1. padding设置

.parent {
    background-color: red;
    /* 利用父盒子的padding实现子盒子的居中 */
	padding: 20px;
 }
.child {
   height: 200px;
   background-color: blue;
}

2. 使用flex布局

.parent {
  height: 200px;
  background-color: red;
  display: flex;
  align-items: center;
  justify-items: center;
}
.child {
  width: 100px;
  height: 100px;
  background-color: blue;
}

3. 使用伪元素

.parent {
  height: 200px;
  background-color: red;
  text-align: center;
}
.child {
  width: 100px;
  height: 100px;
  display: inline-block;
  background-color: blue;
  /*行内块元素对齐的特点设置垂直居中*/
  vertical-align: middle;
}

.parent::before {
	content: '';
	display: inline-block;
	width: 20px;
	height: 200px;
	vertical-align: middle;
	/* background-color: green; */
}

4. calc函数

盒子的宽高度相同

.parent {
  weight: 600px;
  height: 600px;
  background-color: red;
}
.child {
  width: 100px;
  height: 100px;
  padding: calc((100% - 100px) / 2);
  background-color: blue;
 /* 背景颜色只对content生效,不对padding生效 */
  content-clip: content-box;
}

视频详见
【超全面的CSS居中方法总结-哔哩哔哩】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值