Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flexbox to center dynamical objects

Tags:

html

css

flexbox

When the game starts, flexbox centering works great (on static objects). During the game progress both (title and remain divs) change their values/sizes, so that causes to constantly adjusting center positioning by flexbox (all divs in header are moving).

I want each div inside header to stay "fixed" during the game.

Is that possible just by using flexbox or should i use another approach? Should I position each element individually?

You can watch header behaviour on the remote server: https://stacho163.000webhostapp.com/firstLevel.html

body {
  margin: 0;
  width: 100%;
  height: 100%;
}

header {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: white;
}

#game-window {
  position: absolute;
  width: 90vw;
  height: 90vw * 16/9;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -46%);
  background-color: gray;
}
<body>
  <header>
    <div id="lifes">
      Life1 Life2 Life3
    </div>
    <div id="title">
      Title (changes when you win)
    </div>
    <div id="remain">
      Remaining: (from 100 to 0)
    </div>
  </header>
  <canvas id="game-window"></canvas>
</body>

https://jsfiddle.net/nfzj183t/14/

I am asking, as I don't have much experience in web stuff and i want to use the correct approach to solve this simple problem.
Thank you in advance for your tips :)

like image 589
Smooth Coding Avatar asked Feb 03 '26 19:02

Smooth Coding


1 Answers

One approach could be to use grid for the main layout and inside every element of grid, use flexbox components.

header would be something like:

header {
  display: grid;
  grid-template-columns: repeat(3,1fr);
  grid-template-rows: 10vh;
}

And you will need to make every column a "display: flex;" container. This would be an example with the "lifes":

#lifes{
  display: flex;
  align-items: center;
  justify-content: center;
}

I can show you more complex examples if needed.

Reference: https://gridbyexample.com/examples/

like image 154
AngelMdez Avatar answered Feb 06 '26 10:02

AngelMdez