整理下初学时做过的js基础编程题目和大家分享以下,如果大家觉得有用,别忘了点一下赞哦
css实现元素水平垂直居中
css水平、垂直居中的写法,请至少写出4种?
- 定位 -- 使用 margin-top:- 盒子的高度一半
- Flex
- Transform
- 定位 -- 使用 上下左右都为 0 ,margin:auto
- js盒模型 -- 利用js盒模型 clientWidth
首先我得有两个嵌套的元素
html部分
//结构
<div class="wrap">
<div class="inner"></div>
</div>
//样式
.wrap {
width: 500px;
height: 500px;
background-color: #ccc;
}
.inner {
width: 300px;
height: 300px;
background-color: pink;
}
- 第一种:定位
.wrap {
position: relative;
}
.inner {
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
- 第二种:定位
.wrap {
position: relative;
}
.inner {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
- 第三种:transform
.wrap {
/* 创建BFC,防止外边距传递 */
overflow: hidden;
}
.inner {
/* 这里的百分比是相对 wrap 元素 */
margin: 50% auto;
/* 这里的百分比是相对 inner 元素 */
transform: translateY(-50%);
}
- 第四种:弹性布局
.wrap {
display: flex;
justify-content: center;//主轴的对齐方式
align-items: center;//侧轴的对齐方式
}
-第五种:盒模型
let inner = document.querySelector('.inner')
let winW = window.innerWidth
let winH = window.innerHeight
//如果找不到,就相对body
inner.style.position = 'absolute'
inner.style.left = (winW - 300) / 2 + 'px'
inner.style.top = (winH - 300) / 2 + 'px'
-第六种 grid布局
.wrap {
display: grid;
justify-content: center;
align-items:center;
}
-第七种 tailwindcss js库
<script src="https://cdn.tailwindcss.com"></script>
<div class="wrap relative">
<div class="inner absolute left-1/2 top-1/2 translate-x-[-50%] translate-y-[-50%]"></div>
</div>
-第八种 bootstrap css库
链接:tailwind学习地址
现在是Sun Nov 21 2021 22:10:16 GMT+0800 (中国标准时间),我刚刚面试遇到一个水平垂直居中的坑。
div为300px*300px,使div水平垂直居中
<body>
<div></div>
</body>
注意点:body没有高度为0,要先给body设置高度。