常用弹性盒例子及栅格布局(设置每行盒子固定个数)(分别在水平方向和竖直方向的均匀分布、两端对齐、完美居中(水平垂直居中))(弹性盒真的是YYDS)

这里分享几个常用的例子,其他的具体的就参考 https://www.runoob.com/css3/css3-flexbox.html

完美居中(水平垂直居中)

举个例子:
CSS:

.flex-container {
    display: flex;
	justify-content: center;
	align-items: center;
    width: 400px;
    height: 250px;
    background-color: lightgrey;
}

HTML:

<div class="flex-container">
  <div>盒子</div>
</div>

效果图:
在这里插入图片描述

均匀分布(space-around),两端对齐(space-between)(水平方向)

举个例子:
CSS:

.flex-container {
    display: flex;
	justify-content: space-around; //均匀分布(两端对齐属性改为space-between,其他属性可以参考上面的的w3c链接)
    width: 400px;
    height: 250px;
    background-color: lightgrey;
}
.flex-item{
		width:50px;
	    height:50px;
	    background-color: red;
	}

HTML:

<div class="flex-container">
  <div class="flex-item">盒子1</div>
  <div class="flex-item">盒子2</div>
  <div class="flex-item">盒子3</div>
</div>

均匀分布效果图:
在这里插入图片描述
两端对齐效果图:
在这里插入图片描述

均匀分布,两端对齐(上下对齐)(垂直方向)

默认是水平方向,也就是所谓的X轴,我们想要在垂直方向
使用justify-content进行布局就这个时候就需要用到flex-direction属性将X轴改为Y轴(竖直方向)
举个例子:
CSS:

.flex-container {
    display: flex;
	flex-direction: column;
	justify-content: space-around;(同理两端对齐属性改为space-between)
    width: 400px;
    height: 250px;
    background-color: lightgrey;
}
.flex-item{
		width:50px;
	    height:50px;
	    background-color: red;
	}

HTML:

<div class="flex-container">
  <div class="flex-item">盒子1</div>
  <div class="flex-item">盒子2</div>
  <div class="flex-item">盒子3</div>
</div>

均匀分布效果图:
在这里插入图片描述
两端对齐(上下对齐)效果图:
在这里插入图片描述

多个盒子水平垂直居中布局

举个栗子:
CSS:

.flex-container {
    display: flex;
	flex-direction: column;
	justify-content: center;
    align-items: center;
    width: 400px;
    height: 250px;
    background-color: lightgrey;
}
.flex-item{
		width:50px;
	    height:50px;
	}

HTML:

<div class="flex-container">
  <div class="flex-item">盒子1</div>
  <div class="flex-item">盒子2</div>
  <div class="flex-item">盒子3</div>
</div>

效果图:
在这里插入图片描述

多个盒子栅格布局(每行固定盒子个数)

html代码

<div class="flex-container">
  <div class="flex-item">盒子1</div>
  <div class="flex-item">盒子2</div>
  <div class="flex-item">盒子3</div>
  <div class="flex-item">盒子4</div>
  <div class="flex-item">盒子5</div>
  <div class="flex-item">盒子6</div>
  <div class="flex-item">盒子7</div>
  <div class="flex-item">盒子8</div>
  <div class="flex-item">盒子9</div>
</div>

css代码

.flex-container{
dispaly: grid; // 启用栅格布局
grid-template-columns: repeat(5, 1fr); 每行盒子个数为5
background-color: lightgrey;
}
.flex-item{
        background-color: red;
		width:50px;
	    height:50px;
}

觉得有用的童鞋给作者点个赞再走呗!蟹蟹!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值