元素居中的方法

本文详细介绍了如何使用各种方法实现行内元素的垂直和水平居中,包括单行文本、多行文本和块级元素的居中处理,涵盖了`vertical-align`、`position`、`flexbox`等技术。同时,提供了实例代码和常见居中策略的实践应用。

一、行内元素的居中方法

1、单行文本垂直居中

.center {
 	// 完全可以不设置高度
 	// height: 20px;
 	line-height: 20px;
}

2、多行文本垂直居中——vertical-align

<div class="box">
	<div class="center">
	啦啦啦啦啦啦
	</div>
</div>
<style>
.box {
	background-color: orange;
	line-height: 200px;
	width: 300px;
}
.center {
	background-color: green;
	line-height: 20px;
	display: inline-block;
	vertical-align: middle;
}
</style>
复制代码

2、.table-cell(不是很常用)

.box {
       height: 23px;
       display: table-cell;
       vertical-align: middle;
}

行内元素水平居中

       text-align: center;

二、块级元素居中

水平居中

margin: 0 auto;

垂直居中

1、.position(居中元素宽高固定)父绝子相

.box {
	position: relative;
}
.center {
	position:absolute;
	width: 200px;
	height: 200px;
	top:0;
	bottom:0;
	left:0;
	right:0;
	margin: auto;
}

 2、vertacal-align

<div class="box">
    <div class="assist"></div>
    <div class="center"> 
       啦啦啦啦啦
    </div>
</div>
<style>
.box {
    background-color: orange;
    height: 200px;
    width: 500px;
    text-align: center;
}
.center {
    background-color: green;
    width: 150px;
    display: inline-block;
    vertical-align: middle;
}
.assist {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
</style

3、position配合margin

<div class="box">
    <div class="center"> 
啦啦啦啦啦啦
    </div>
</div>
<style>
.box {
    background-color: orange;
    height: 200px;
    width: 500px;
    position: relative;
}
.center {
    background-color: green;
    width: 150px;
    height: 50px;
    position:absolute;
    top:50%;
    left:50%;
    margin-left: -75px;
    margin-top: -25px;
}
</style>

4、position配合transform

<div class="box">
    <div class="center"> 
       啦啦啦啦啦啦啦啦啦啦
    </div>
</div>
<style>
.box {
    background-color: orange;
    height: 200px;
    width: 500px;
    position: relative;
}
.center {
    background-color: green;
    width: 150px;
    position:absolute;
    top:50%;
    left:50%;
    transform: traslate(-50%, -50%);
}
</style>

5、flex

.box {
    display: flex;
    align-items: center;
    justify-content: center;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值