Reputation: 37
I'm writing a game of pong in JavaScript, and I need the ball to be a square for obvious reasons. I'm using percentage measurements so the game works on all resolutions, but I was wondering how to make the ball a square using these.
#ball{
position: absolute;
height: 1.5%;
width: 1.5%;
background-color: white;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
}
Obviously 1.5% of the width is a lot more than 1.5% of the height. Does anyone know how to make these two the same in pixels, without sacrificing flexibility?
Upvotes: 2
Views: 48
Reputation: 17664
instead of height
, you can use percentage padding-bottom
(or padding-top
):
#ball {
position: absolute;
width: 3.5%;
background-color: red;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
padding-bottom: 3.5%;
}
<div id="ball"></div>
Upvotes: 1
Reputation: 122155
You could use viewport units vh
or vw
where size depends on window size so it will be flexible relative to window size but not parent element size.
.square {
width: 10vw;
height: 10vw;
border: 1px solid black;
margin: 50px;
}
<div class="square"></div>
Upvotes: 2
Reputation: 4281
Instead of using percentages, I would recommend to use rem units, which is responsive as well.
#ball {
width: 1.5rem;
height: 1.5rem;
border: 1px solid #000;
background: #f00;
}
<div id="ball"></div>
Upvotes: 0
Reputation: 669
Try this
#ball {
position: absolute;
height: 1.5%;
width: 1.5%;
max-height: 1.5%;
max-width: 1.5%;
background-color: #d84343;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
padding: 38px 30px;
}
Or use in pixel
#ball {
position: absolute;
height: 80px;
width: 80px;
background-color: #d84343;
top: 50%;
left: 50%;
margin-top: -12.5px;
margin-left: -12.5px;
}
Upvotes: 0