设置元素居中(前端面试题)

7 篇文章 0 订阅

水平居中

行内元素
设置text-align:center
块级元素
1.先定义一个宽高,再根据margin的左右移动来居中
2.使用绝对定位的四个属性来居中且margin:auto;
3.使用绝对定位,然后设置left top的值为50%,在使用
transform:translate(-50%,-50%);
4.需要剧中的元素设置为display:inline-block;然后其父元素设置为text-aligin:center;
5.通过设置浮动
6.设置弹性布局
display:flex;
justify-content:center

水平垂直居中

1.弹性布局,为父元素设置
			display:flex;
		  justify-content:center;
		  align-items:center;
2.position定位
		父元素设为fixed,上下左右都为0,margin设置为auto。子元素设为fixed,上下左右都为0,margin设置为auto。
position: fixed;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		margin: auto;
3.使用绝对定位

```html
/*此方法是在给定宽高的情况下;且父元素需要设置相对定位以便给子元素一个相对位置*/
	.one{
		width: 200px;
		height: 200px;
		background-color: lightblue;
		position: absolute;
		left: 50%;
		top: 50%;
		/*margin: -100px 0 0 -100px;*/
		transform:translate(-50%,-50%);
		//或者margin-top:-100px;margin-left:-100px
	}
	4.父元素设置position:relative,子元素设置position:absolute;上下左右都为0,margin设置auto
	

```html
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>

<body>
<div class="one">
	<div class="two">
		
	</div>
</div>
</body>
<style type="text/css">
	
	.one{
		width: 200px;
		height: 200px;
		background-color: lightblue;
		position: relative;
		
	}
	.two{
		width: 100px;
		height: 100px;
		background-color: red;
		position: absolute;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		margin: auto;
	}
</style>
</html>
5.父元素设置display:flex;子元素margin:auto
<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>

<body>
<div class="one">
	<div class="two">
		
	</div>
</div>
</body>
<style type="text/css">
	
	.one{
		width: 200px;
		height: 200px;
		background-color: lightblue;
		

		display: flex;
		
	}
	.two{
		width: 100px;
		height: 100px;
		background-color: red;
		
		margin: auto;
	}
</style>
</html>

新发现一种可以水平垂直居中的方式:display:table-cell
dom片段:

<div class="one">
    <div class="wto"></div>
</div>

css片段:

.one{
            width: 500px;
            height: 300px;
            border: 1px solid red;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
        .wto{
            display: inline-block;
            border: 1px solid green;
            width: 50px;
            height: 50px;
        }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值