CSS3 弹性布局 使用Flexbox(一)垂直居中文本、偏移、反序的实现

本文介绍了CSS3的Flexbox布局,重点讲解了如何实现垂直居中文本、元素偏移以及反序排列。通过示例代码展示了display: flex;、align-items: center; 和 justify-content: center; 的作用,以及如何通过修改flex-direction实现元素的反序。同时提到了flex-flow属性的使用,帮助初学者更好地理解和应用Flexbox。

Flexbox有四个关键特性:方向、对齐、次序和弹性。

下面利用几个简单的示例,只涉及几个元素盒子以及他们周围的内容。以方便我们理解Flexbox。

一、完美 垂直居中文本

代码如下:

<div class="Header">
				hello world!(垂直居中)
</div>

垂直居中文本的CSS规则如下:

<style>
.Header{
	width: 400px;
	height: 130px;
	background-color: #038c5a;
	color: #ebebeb;
	font-family: 'Oswald',sans-serif;
	font-size: 2rem;
	text-transform: uppercase;
	/*文字垂直居中*/
	display: flex;
	align-items: center;
	justify-content: center;
}

</style>

下面三个属性实现了文字垂直居中:

 

 其中:

       display: flex;这是Flexbox的根本所在。就是把当前元素设置为一个Flexbox(而不是block或inline-block之类)。

       align-items: center;   这是要在Flexbox中沿交叉轴对齐项目。上面是要实现垂直居中文本。

       justify-content: center;   这里设置内容沿主轴居中。类似于,word软件中用于左、中、右对齐文本的按钮。

二、偏移

标记如下:

<div class="Header2">
	<a href="#" class="ListItem">首页</a>
	<a href="#" class="ListItem">关于我们</a>
	<a href="#" class="ListItem">产品</a>
	<a href="#" class="ListItem">活动</a>
	<a href="#" class="LastItem">联系我们</a>
</div>

 CSS如下:

<style>
.Header2{
	width: 400px;
	background-color: indigo;
	font-family: 'Oswald', sans-serif;
	font-size: 1rem;
	min-height: 2.75rem;
	display: flex;
	align-items: center;
	padding: 0 1rem;
}
.ListItem,
.LastItem {
	color: #ebebeb;
	text-decoration: none;
}

.ListItem {
	margin-right: 1rem;
}

.LastItem {
	margin-left: auto;
}

</style>

 在包含元素div上设置display: flex;其子元素就会变成弹性项(flex-item),从而在弹性布局模型下布局。

最后,margin-left: auto;他让最后一项用上该侧所有可用的外边距。

三、反序

 只需将第二部分中的css稍加改动。

  • 给包含元素即div的css加一行:flex-direction: row-reverse;  
  • 把最后一项 .lastItem的margin-left: auto;改为margin-right: auto;
<style>
.Header2{
	width: 400px;
	background-color: indigo;
	font-family: 'Oswald', sans-serif;
	font-size: 1rem;
	min-height: 2.75rem;
	display: flex;
        flex-direction: row-reverse;
	align-items: center;
	padding: 0 1rem;
}
.ListItem,
.LastItem {
	color: #ebebeb;
	text-decoration: none;
}

.ListItem {
	margin-right: 1rem;
}

.LastItem {
	margin-right: auto;
}

</style>

1、垂直排列:(使所有项垂直堆叠排列):在包含元素中使用flex-direction:column; 在把自动外边距属性删掉:

<style>
.Header2{
	width: 400px;
	background-color: indigo;
	font-family: 'Oswald', sans-serif;
	font-size: 1rem;
	min-height: 2.75rem;
	display: flex;
        flex-direction: column;
	align-items: center;
	padding: 0 1rem;
}
.ListItem,
.LastItem {
	color: #ebebeb;
	text-decoration: none;
}

.ListItem {
	margin-right: 1rem;
}

</style>

2、垂直反序:

只需要改成:flex-direction:column-reverse;

 

此外:flex-flow属性,是flex-direction和flex-wrap的合体。比如:flex-flow:row wrap;  初学者可以分开设置两个属性,更清楚一些。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值