如何在不移动画布的情况下定位.container?

时间:2019-07-02 07:46:17

标签: javascript html css

我尝试将.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;

4 个答案:

答案 0 :(得分:1)

我已经更新了CSS。如果您有任何疑问,请随时询问:)

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;
}

canvas#cv {
  background: #1b1b5d;
  height: 100vh;
  width: 100vw;
}

.container {
  position: absolute;
  width: 100vw;
}

.wrapper {
  margin: auto;
  text-align: center;
  width: 600px;
  margin-top: 50px;
}
<div class="container">
  <div class="wrapper">
    <input type="text" />
    <input type="text" />
  </div>
</div>
<canvas id="cv"></canvas>

答案 1 :(得分:1)

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

答案 2 :(得分:0)

.contianer {
 position: fixed;
}

通过使用固定属性,您可以根据视口对其进行修复。 如果您只想按父母使用 那么您的解决方案应该可以工作

答案 3 :(得分:0)

在您的CSS中尝试一下:

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;
}



#cv {
	padding-left: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 400px;
    background: green;

}

.container{

	padding-left: 0;
    padding-right: 0;
    margin: 50px auto 10px auto;
    display: block;
    width: auto;
    height: auto;
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<link rel="stylesheet" href="forhelp.css">
	<title>CANVAS IN CENTER</title>
</head>
<body>
<div class="container">
 <input type="text"/>
 <input type="text"/>
</div>
<canvas id="cv"></canvas>
</body>
</html>