html垂直居中的方法

1.行高法line-height(适用于单行或较少几个文字)

设置文字的行高和容器的高度相同

<div id="div1">
      单行文本或几个字的垂直居中
    </div>
<style>
	#div1{
	    width: 300px;height: 100px;/* 设置容器的宽高 */
	    margin: 100px auto;/* 使容器水平边距自动相等 */
	    border: 1px solid red;/* 给文本加上边框可以更清楚地看到效果 */
	    line-height: 100px; /*设置line-height与rongqi的height相等*/
	    text-align: center; /*设置文本水平居中*/
	    overflow: hidden; /*防止内容超出容器或者产生自动换行*/
</style>

在这里插入图片描述

2.多行文本-内容填充padding

简单来说就是把文字挤到中间,此时容器高度不固定

<div id="div1">
        多行文本的垂直居中
		多行文本的垂直居中
		多行文本的垂直居中
		多行文本的垂直居中
		多行文本的垂直居中
    </div>
<style>
	#div1{
	    width: 300px;
	    margin: 100px auto;/* 使容器水平边距自动相等 */
	    border: 1px solid red;/* 给文本加上边框可以更清楚地看到效果 */
	    line-height: 100px; /*设置line-height与rongqi的height相等*/
	    text-align: center; /*设置文本水平居中*/
	   padding:50px 20px;}
</style>

在这里插入图片描述

3.多行文本-用vertical-align,div模拟tabel

vertical-align只对有valign特性的元素才生效

 <div id="div1">
	<div id="div2">
		 多行文本的垂直居中
		 多行文本的垂直居中
		 多行文本的垂直居中
		 多行文本的垂直居中
		 多行文本的垂直居中
	 </div>
</div>
<style>
	#div1{
	    width: 300px;height: 200px;
	    margin: 100px auto;/* 使容器水平边距自动相等 */
	    border: 1px solid red;/* 给文本加上边框可以更清楚地看到效果 */
	    display: table;
		}
	#div2{
		display: table-cell;
		vertical-align: middle;
		text-align: center;
		width: 100%;
	}
</style>

在这里插入图片描述

4.子容器的垂直居中-定位移动

子绝父相,根据子容器的大小进行定位移动

 <div id="div1">
	<div id="div2">
		 子容器的垂直居中
	 </div>
</div>
<style>
	#div1{
	    width: 300px;height: 200px;
	    background-color: #ccc;
		position: relative;
		}
	#div2{
		width: 100px;height: 100px;
		background-color: #FB7299;
		margin: auto;
		position: absolute;
		left: 50%;top:50%;
		margin-top: -50px;margin-left: -50px;
	}
</style>

在这里插入图片描述

  • 7
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值