This question already has an answer here:
- How to horizontally center a <div>? 101 answers
- How to vertically center a div for all browsers? 44 answers
I am building a school project, were supposed to build a board game, so far I've made the actual board with the help of a grid and a few lines of js.
Now I thought I was doing the easy part of centering the container div to its container the browser, but oh my no way! So far have none of the normal ways have done what I want... so now I turn here. Most important is to center it horizontal... secondly verticaly.
Heres the code so far:
function drawBoard() {
for (gridrow=0; gridrow<12; gridrow++) {
for (gridcolumn=0; gridcolumn<15; gridcolumn++) {
var customClass=(gridcolumn+'-'+gridrow);
var parent = document.getElementById('boardgame');
var divnode = document.createElement('div');
var attribute = document.createAttribute('class');
if(isEven(gridrow)) {
if(isEven(gridcolumn)) {
attribute.value = customClass+' frame'+' light-floor-2';
} else {
attribute.value = customClass+' frame'+' dark-floor-2';
}
} else {
if(isEven(gridcolumn)) {
attribute.value = customClass+' frame'+' dark-floor-2';
} else {
attribute.value = customClass+' frame'+' light-floor-2';
}
}
divnode.setAttributeNode(attribute);
parent.appendChild(divnode);
}
}
}
function isEven(n){
if(n % 2 == 0){
return true;
} else {
return false;
}
}
.container {
margin: 0 auto;
width: 100%;
}
.innerframe {
display: grid;
grid-template-columns: repeat(15, auto);
grid-template-rows: repeat(12,auto);
height: 720px;
width: 900px;
z-index: 1;
}
.light-floor-1 {
background-image: url("../img/light_floor_1.png");
}
.light-floor-2 {
background-image: url("../img/light_floor_2.png");
}
.dark-floor-1 {
background-image: url("../img/dark_floor_1.png");
}
.dark-floor-2 {
background-image: url("../img/dark_floor_2.png");
}
<!doctype html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title>Drakborgen</title>
<link rel="stylesheet" href="css/board.css">
<script src="js/site.js" async></script>
</head>
<body>
<div id="container">
<div id="boardgame" class="innerframe"></div>
<div id="gameboard" class="gameframe">
</div>
</div>
<script>
window.onload = function() {
drawBoard();
}
</script>
</body>
</html>
That container div is a try I did but no nothing. I tried to use flexbox but no. As you can see I got more to do... the boardgame div and the gameboard div should be on top of each other, but I am not there yet.
来源:https://stackoverflow.com/questions/58316890/a-css-grid-that-needs-to-center-on-page-how