javascript - 如何在不移动画布的情况下定位 .container?
问题描述
我尝试将 .container 居中,但将画布保持在原位。我怎样才能做到这一点?
HTML:
<div class="container">
<input type="text"/>
<input type="text"/>
</div>
<canvas id="cv"></canvas>
CSS:
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
html{
overflow: hidden;
}
.container{
position: absolute;
left: 100px;
top: 150px;
}
JavaScript:
var canvas = document.getElementById("cv");
let width = window.innerWidth * 0.99;
let height = window.innerHeight * 0.97;
canvas.width = width;
canvas.height = height;
解决方案
您可以使用transform:translate(-50%,-50%)
使其垂直和水平居中来做到这一点
var canvas = document.getElementById("cv");
let width = window.innerWidth * 0.99;
let height = window.innerHeight * 0.97;
canvas.width = width;
canvas.height = height;
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
html {
overflow: hidden;
}
.container {
position: absolute;
left: 50%;
top: 50%;
transform:translate(-50%,-50%);
text-align:center;
width:100%;
}
#cv {
background: red;
height: 100%;
}
<div class="container">
<input type="text" />
<input type="text" />
</div>
<canvas id="cv"></canvas>
推荐阅读
- r - charToDate(x) 中的错误:字符串在 r 中不是标准的明确格式
- r - 如果长度不等,则合并两个列表的列表元素
- php - PhpStorm ShortCut 创建函数
- r - 将二进制向量转换为二进制矩阵
- angular - Angular:在另一个组件中访问组件的nativeElement
- c# - 编写程序查找数组中 Max 项的索引
- bash - bash 是否泄漏内存?
- vue.js - 当输入框达到一定长度时,我可以执行方法吗?
- visual-studio-2017 - lib 内置 vs c++ 2005 如何在 vs 2017 中使用它们?
- php - 我可以将包添加到没有 flex 配方的 Symfony 4 项目吗?