• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

让div在页面居的方法

武飞扬头像
绝世狂刀客
帮助1

第一种方法

<style>
	html,body{
		height:100%;
	}
	body{
		position:relative;
		margin:0;
	}
	.container{
		position:absolute;
		top:50%;
		height:50%;
		transform:translate(-50%,-50%);
	}
</style>

<body>
	<div class="container">正中心的盒子</div>
</body>
学新通

说明:

  1. 设置父元素为relative,子元素为absolute可以使子元素相对于父元素进行绝对定位。
  2. 设置left和top,各是页面的50%的大小
  3. 然后使用transfrom:translate(-50%,-50%);使元素自身在水平和竖直方向,向左和向上偏移自身的50%,从而达到使容器在页面的正中心的目的。
  4. 给html和body(即父元素)添加height属性是必要的。

第二种方法

<style>
    html,body{
        height: 100%;
        margin: 0;
    }
    .container{
        display: flex;
        justify-content: center;
        align-items: center;
        /*以上三行是关键代码*/
        width: 100%;
        height: 100%;
        background-color: antiquewhite;
    }
    .box{
        width: 300px;
        height: 300px;
        background-color: aqua;
    }
</style>
<body>
    <div class="container">
        <div class="box">我是正中心的盒子</div>
    </div>
</body>
学新通

说明:

  1. 设置html和body的高度占满浏览器(必要),去除掉外边距(非必要)
  2. 设置以下属性
.container{
	display:flex;/*弹性盒子布局*/
	justify-content:center;/*水平排列方式设定*/
	align-items:center;/*垂直排列方式设定*/
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhchhfgi
系列文章
更多 icon
同类精品
更多 icon
继续加载