每日一知识:css居中的总结

准备以后每天分享一两个知识点,一方面方便自己复习,另一方面转移一下笔记。

第一天先从css居中开始:

一.宽高固定

1.绝对定位+margin:auto

	 position: absolute;
	 top: 0;
	 left: 0;
	 right: 0;
	 bottom: 0;
	 margin:auto;
	 //盒子大小不确定,被内容撑开时,这么写不行会把视角撑满

2.绝对定位+负margin

// 涉及到具体的px,因此不太推荐使用
.box {
    width: 200px;
    height: 200px;
 	background: green;
    position: relative;
}
.child  {
    width: 100px;
    height: 100px;
    background: yellow;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px; 
}

3.绝对定位+transform

//该方式是我最常用的,是个万能居中方案,不管有没有宽高都可以居中

.box {
    width: 200px;
    height: 200px;
 	background: green;
    position: relative;
}
.child  {
	/*
    width: 100px;
    height: 100px;
	*/
	position: absolute;
	/*原理: 绝对定位元素是相对于包含块进行定位的 平移是相对于自己平移的 */
	left: 50%;
	top: 50%;
	transform: translateX(-50%) translateY(-50%);
	/*此时不管内容是什么,盒子都居中*/
}

4.flex布局

//很常用

.box {
    width: 200px;
    height: 200px;
    border: 1px solid red;
    display: flex;
    justify-content: center;
    align-items: center;
}
.child  {
    background: yellow;
    height: 100px;
    width: 100px;
}

5.网格布局

// 对网格布局不太熟悉的话看一下菜鸟的文档复习一下
.box {
    width: 200px;
    height: 200px;
    border: 1px solid red;
    display: grid;
}
.child  {
    width: 100px;
    height: 100px;
    background: yellow;
    margin: auto;
}

二.不定宽高

1.绝对定位 + transform

// 上面已经说过这个是万能居中的方案
.box {
    width: 200px;
    height: 200px;
    position: relative;
}
.child  {
   position: absolute;
   background: yellow;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

2.flex布局

.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  display: flex;
  align-items: center; // 纵轴对齐方式,默认是纵轴 子元素垂直居中
  justify-content: center; //纵轴对齐方式,默认是纵轴
}
.child {
  background: red;
}  

或者给子元素设置margin:auto

.box {
  width: 200px;
  height: 200px;
  border: 1px solid;
  display: flex;
}
.child {
  background: red;
  margin: auto; // 水平垂直居中
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值