css 常见的水平 垂直居中布局

  1. 思路
    内联元素居中布局
    水平居中:
    行内元素可设置:text-align: center
    flex布局设置父元素:display: flex; justify-content: center

    垂直居中:
    单行文本父元素确认高度:height === line-height ,设置height, line-height
    多行文本父元素确认高度:disaply: table-cell; vertical-align: middle

    块级元素居中布局
    水平居中:
    定宽: margin: 0 auto

    垂直居中:
    position: absolute设置left、top、margin-left、margin-to(定高)
    position: fixed设置margin: auto(定高)
    display: table-cell
    transform: translate(x, y)
    flex(不定高,不定宽)

  2. css实现(其他样式代码自己补全)

	<div id="app">
        <div class="parent">
            <div class="children"></div>
        </div>
    </div>
.parent{
	width:200px;
	height:200px;
}
.children{
	width:50px;
	height:50px;
	background-color: rgb(255, 181, 25);
}

方法一:绝对定位 负magin值
//添加相对定位
.parent{
	position: relative;
}
.children{
	position: absolute;
	top:50%;
	left:50%;
	margin-top:-25px;
	margin-left:-25px;
}

方法二: 绝对定位 transform
.parent{
	position: relative;
}
.children{
	position: absolute;
	top:50%;
	left:50%;
	transform:translate(-50%, -50%);
}
方法三:定位 + left/right/bottom/top + margin
.parent{
	position: relative;
}
.children{
	position: absolute;
	top:0;
	left:0;
	bottom:0;
	right:0;
	margin:auto;
}
方法四:使用flex布局
.parent{
	display:flex;
	justify-content: center;
    align-items: center;
}
方法五:table-cell布局
.parent{
	display: table-cell;
	text-align: center;
    vertical-align: middle;
}
.children{
	display: inline-block;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值