Gergő Horváth
Gergő Horváth

Reputation: 3705

How to write a square which is always at the center of the screen, and touches shorter edges?

The task is to draw a square which is always at the center of the screen, and the left and right or top or bottom edges are always at the edges of the screen. If we know the screen orientation, it's easy.

If portrait: (I set the "screen", in real the square's height and width are 100vw)

.screen{
  width: 200px;
  height: 400px;
  border: 1px solid black;
  display: flex;
}
.square{
  background-color: red;
  width: 200px;
  height: 200px;
  margin: auto;
}
<div class="screen">
  <div class="square"></div>
</div>

If landscape:

.screen{
  width: 100vw;
  height: 100vh;
  border: 1px solid black;
  display: flex;
}
.square{
  background-color: red;
  width: 100vh;
  height: 100vh;
  margin: auto;
}
<div class="screen">
  <div class="square"></div>
</div>

But we don't know the screen orientation, and we can't use JavaScript. Do you have any only CSS idea which solves the problem?

Upvotes: 0

Views: 707

Answers (2)

Quentin
Quentin

Reputation: 3289

You need to use max-width and max-height for that.
This way, the square will always fit the screen whether it is a landscape screen or a portrait screen.

.square {
  width: 100vw;
  height: 100vw;
  max-width: 100vh;
  max-height: 100vh;
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
  background: red;
}

body {
  margin: 0;
}
<div class="square"></div>

Upvotes: 1

Gabbr Issimo
Gabbr Issimo

Reputation: 111

You can know the screen orientation from media queries

@media (orientation: landscape) {
  /////
}

@media (orientation: portrait) {
  //////
}

Upvotes: 1

Related Questions