首页 前端知识 【盒子水平垂直居中的三种(四种)方式】

【盒子水平垂直居中的三种(四种)方式】

2024-03-12 01:03:38 前端知识 前端哥 578 777 我要收藏

【盒子水平垂直居中的三种(四种)方式】

        • 效果
        • 方法一:利用margin:auto
        • 方法一:利用定位(子绝父相)
        • 方法三:利用flex布局
        • 方法四:利用计算外边距(和margin:auto相似)

效果

在这里插入图片描述

方法一:利用margin:auto

margin: auto;和 margin-top: ;搭配使用

<style>
* {
padding: 0;
margin: 0;
}
.parent {
position: fixed;
width: 900px;
height: 600px;
background-color: aqua;
}
.children {
margin: auto;
margin-top: 150px;
width: 300px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">
</div>
</div>
</body>
复制
方法一:利用定位(子绝父相)

父盒子使用相对定位,子盒子使用绝对定位,利用top:50% left:50% 让子盒子相距父盒子上边界,左边界宽高的50% 利用 margin-top margin-left返回子盒子自身宽高的50%

<style>
* {
padding: 0;
margin: 0;
}
.parent {
position: relative;
width: 900px;
height: 600px;
background-color: aqua;
}
.children {
position: absolute;
top: 50%;
/* 相当于父盒子高度的50% */
left: 50%;
/*相对于父盒子宽度的50%*/
margin-top: -150px;
/*向上走回自身高度的一半*/
margin-left: -150px;
/*向左走回自身宽度的一半*/
width: 300px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="parent">
<div class="children">
</div>
</div>
</body>
复制
方法三:利用flex布局
<style>
* {
padding: 0;
margin: 0;
}
.parent {
display: flex;
/* x轴居中 */
justify-content: center;
/* y轴居中 */
align-items: center;
width: 900px;
height: 600px;
background-color: aqua;
}
.children {
width: 300px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
复制
方法四:利用计算外边距(和margin:auto相似)
<style>
* {
padding: 0;
margin: 0;
}
.parent {
position: fixed;
width: 900px;
height: 600px;
background-color: aqua;
}
.children {
/* 距离上侧150px */
margin-top: 150px;
/* 距离左侧300px */
margin-left: 300px;
width: 300px;
height: 300px;
background-color: pink;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
复制
转载请注明出处或者链接地址:https://www.qianduange.cn//article/3672.html
标签
评论
发布的文章

jquery监听input值改变

2024-04-08 11:04:31

jquery 笔记

2024-04-08 11:04:27

jQuery Ajax前后端数据交互

2024-04-08 11:04:24

JQuery入门基础

2024-02-20 10:02:06

JQuery中的事件对象

2024-04-08 11:04:16

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!