0
votes

How do you auto-resize a large image so that it will fit into a smaller width flex container whilst maintaining its width:height ratio?

Also, the solution must not relate on vw / vh, so that on a page there can be more in addition to this component.

Here's how it should look like:

enter image description here


Here's my code:

body {
  margin: 0;
}
.wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.header {
  flex: 0 0 100px;
  background-color: cornflowerblue;
}
.content {
  text-align: center;
}
.image {
  width: 100%;
  height: 100%;
}
.footer {
  flex: 0 0 100px;
  background-color: cornflowerblue;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Images Are Weird</title>
  </head>
  <body>
    <div class="wrapper">
      <div class="header"></div>
      <div class="content">
       <img class="image" src="https://villagesquare.me/wp-content/uploads/2018/07/Facebook-Square.png" alt="square placeholder" />
      </div>
      <div class="footer"></div>
    </div>
  </body>
</html>

The solutions I found here do not help

2

2 Answers

-1
votes

Just change the image class width to less than 100% like 50% 60% or 70;

body {
  margin: 0;
}
.wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.header {
  flex: 0 0 100px;
  background-color: cornflowerblue;
}
.content {
  text-align: center;
}
.image {
  width: 50%;
  height: 100%;
}
.footer {
  flex: 0 0 100px;
  background-color: cornflowerblue;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Images Are Weird</title>
  </head>
  <body>
    <div class="wrapper">
      <div class="header"></div>
      <div class="content">
       <img class="image" src="https://villagesquare.me/wp-content/uploads/2018/07/Facebook-Square.png" alt="square placeholder" />
      </div>
      <div class="footer"></div>
    </div>
  </body>
</html>
-1
votes

You can also do it by calculating .content width and minus as much as you need.like below...

.content {
    width:calc(100% - 100px);
    margin:0 auto;
}

body {
  margin: 0;
}
.wrapper {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.header {
  flex: 0 0 100px;
  background-color: cornflowerblue;
}
.content {
  width:calc(100% - 100px);
  margin:0 auto;
}
.image {
  width: 100%;
  height: 100%;
}
.footer {
  flex: 0 0 100px;
  background-color: cornflowerblue;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Images Are Weird</title>
  </head>
  <body>
    <div class="wrapper">
      <div class="header"></div>
      <div class="content">
       <img class="image" src="https://villagesquare.me/wp-content/uploads/2018/07/Facebook-Square.png" alt="square placeholder" />
      </div>
      <div class="footer"></div>
    </div>
  </body>
</html>