首页 > 解决方案 > 如何在不移动画布的情况下定位 .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;

标签: javascripthtmlcss

解决方案


您可以使用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>


推荐阅读