水平垂直居中问题

2 篇文章 0 订阅

块级元素居中

1.div使用绝对布局,设置margin:auto;并设置top、left、right、bottom的值相等即可,不一定要都是0。
css代码:

<style>
	.main{
		width: 200px;
		height: 200px;
		background-color: red;
		position: absolute;
		margin: auto;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
	}
</style>

HTML代码:

	<div class="main"></div>

2.仍然是绝对布局,让left和top都是50%,这在水平方向上让div的最左与屏幕的最左相距50%,垂直方向上一样,所以再用transform向左(上)平移它自己宽度(高度)的50%,也就达到居中效果了。

.main{
		width: 200px;
		height: 200px;
		background-color: red;
		position: absolute;
		margin: auto;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%); 
	}

3.使用flex布局,父元素给定宽高:
css样式:

 .box { 
 	background-color: #FF8C00; 
 	width: 300px; 
 	height: 300px; 
 	display: flex;
 	justify-content: center; 
 	align-items: center; 
 	} 
 	.content { 
 		background-color: #F00; 
 		width: 100px; 
 		height: 100px; 
 	}

HTML样式:

<div class="box"> 
	    <div class="content"> </div> 
	</div>

4.还有一种方法,就是display:table;可自行学习;

文本居中

文本居中比较简单,以下是几种常见的方法:
1.第一种就来flex吧,其实和前面一样,代码不用修改就能直接用:
css样式

.box { 
 	background-color: #FF8C00; 
 	width: 300px; 
 	height: 300px; 
 	display: flex;
 	justify-content: center; 
 	align-items: center; 
 	}

html样式

<div class="box">
		你好
	</div>

2.第二种就选line-height属性吧,代码:
css样式

.box { 
 	background-color: #FF8C00; 
 	width: 300px; 
 	height: 300px; 
 	text-align: center;
 	line-height: 300px; 
 	} 

html样式和第一种一样;这种是最常用的文本居中;
3.第三种和第二种有点相似,我们依然使用text-align属性,但垂直居中我们使用vertical-align:middle;这个属性有点特殊,因为它只能作用在inline-block或者inline,还有table-cell等元素内;

 .box { 
 	background-color: #FF8C00; 
 	width: 300px; 
 	height: 300px; 
 	text-align: center;
 	vertical-align: middle; 
 	display: table-cell;
 	} 

4.可以将文本放在一个行内元素中,然后为该行内元素添加属性display:block;;之后就和块元素一样使用定位布局;

若还有什么好的布局方法,请不吝赐教!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值