元素的经典居中问题

相信大家在开发中都会遇到元素的居中问题,而且有些是要跟随浏览器窗口大小的变化但元素永远保持居中位置,下面是我总结的几种常用方法:

1.相对于浏览器窗口居中

css3方法:

	#box{
		width: 200px;
		height: 200px;
		background: pink;
		/*css3居中*/
		position: absolute;/*fixed也行*/
		left: calc(50% - 100px);
		top: calc(50% - 100px);
		}


常规css方法1:

	#box{
		width: 200px;
		height: 200px;
		background: pink;
		position: absolute;
                top: 50%;
		left: 50%;
		margin-left: -100px;
		margin-top: -100px;
		}

常规css方法2:

将上下左右边距(相对于浏览器窗口边缘)全设为0,使浏览器推算出的外边距上下、左右对应相等可以设置任何其他相等的值,但如果窗口小到不能容下任意一个方向的两侧边距,元素也将不居中,所以推荐设为0

	#box{
		width: 200px;
		height: 200px;
		background: pink;
		position: absolute;
                top: 0;
		left: 0;	
		bottom: 0;
		right: 0;
		margin:auto;
		}
注意点:这种方法在相对于父级元素居中的问题上一样可行,下面再添加一个子元素相对于父级元素居中的方法

通过为父元素启用弹性盒布局解决子元素水平垂直居中的问题:

html:

<div class="parent">
     <div class="child"></div>
</div>

css:

	div.parent {
            /* 启用弹性盒布局 */
            display: flex;
            /* 使子元素水平居中 */
            justify-content: center;
            /* 使子元素垂直居中 */
            align-items: center;
            width: 50%;
            height: 200px;
            background-color: aquamarine;
        }

        div.child {
            width: 30%;
            height: 100px;
            background-color: antiquewhite;
        }
效果图:

2.js实现元素相对于浏览器窗口居中问题

		<script type="text/javascript">
			window.onload = function(){
				centerElement("box3");
			}
			
			function centerElement(id){
				//基于浏览器窗口
				var boxDom = document.getElementById(id);
				var cleft = 0;
				var ctop = 0;
				var bw = boxDom.offsetWidth;//需要给盒子设置定位才会生效
				var bh = boxDom.offsetHeight;
				var dw = window.innerWidth;
				var dh = window.innerHeight;
				cleft = (dw - bw)/2;
				ctop = (dh - bh)/2;
				boxDom.style.left =cleft+ "px";
				boxDom.style.top = ctop+"px";
				window.onresize = function(){
					centerElement(id)
				}
			}
		</script>
还有更多关于居中的方法可以点击这里!
以上就是实现元素居中的一些方法,后期如有更好的方法也会继续加进来,或者各位大佬们有好的方法不妨分享一度,阿里嘎多!!!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值