首页 > 其他 > 详细

元素不确定宽高居中

时间:2019-02-26 18:05:35      阅读:153      评论:0      收藏:0      [点我收藏+]

对于确定宽高的元素

简单的来说

我们用margin就可以了

技术分享图片

 

比如上图:

红色框宽高分别是600*300

绿色框宽高分别是400*200

那么,我们可以给绿色的框设置margin:50px 100px;

上下50px 左右100px

.red{
	width: 600px;
	height:300px;
	background: red;
}
.green{
	width: 400px;
	height:200px;
	margin:50px 100px;
	background: green;
}

  或者使用定位:

红色框是position:relative 相对起点定位

绿色框是position:absolute 相对于定位的父元素定位

.red{
	width: 600px;
	height:300px;
	background: red;
	position: relative;
}
.green{
	width: 400px;
	height:200px;
	background: green;
	position: absolute;
	top:50px;
	left:100px;
}

  另一种定位方式

.red{
	width: 600px;
	height:300px;
	background: red;
	position: relative;
}
.green{
	width: 400px;
	height:200px;
	background: green;
	position: absolute;
	top:50%;
	left:50%;
	margin-left:-200px;
	margin-top:-50px;
}

  又或者这样定位

.red{
	width: 600px;
	height:300px;
	background: red;
	position: relative;
}
.green{
	width: 400px;
	height:200px;
	background: green;
	position: absolute;
	top:0;
	left:0;
	right:0;
	bottom:0;
	margin:auto;
}

  当然这些全都有一个前提:宽高确定

如果不确定宽高的情况下,我们可以通过css3来定位居中

.red{
	width: 600px;
	height:300px;
	background: red;
	position: relative;
}
.green{
	background: green;
	position: absolute;
	top:50%;
	left:50%;
	transform: translate(-50%,-50%);
}

  不论是宽或高还是宽高,有任意不确定,都可以这样设置居中

尔等可以试试哈

技术分享图片

 

元素不确定宽高居中

原文:https://www.cnblogs.com/tongjiaojiao/p/10439056.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!