【问题标题】:Keep image aspect ratio and inside a div保持图像纵横比并在 div 内
【发布时间】:2018-09-26 19:06:19
【问题描述】:

我想在 div 内有一个图像(紫色的,见下图),其尺寸以 % 表示,并且图像永远不会从 div 中流出,而是在需要时调整大小,保持纵横比。

目前,我的代码如下,但图片来自 div,如下图所示。

html {
  min-height: 100vh;
  position: relative;
}

body {
  height: 100vh;
  overflow: hidden;
}

#grille {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  flex-direction: row;
  display: flex;
  background-color: red;
}

#colonne {
  width: calc(100% / 3);
  height: 100%;
  background-color: green;
}

#cellule {
  flex-direction: column;
  width: 100%;
  height: calc(100% / 3);
  background-color: aqua;
}

#conteneurImage {
  width: 100%;
  height: 80%;
  background-color: violet;
}

#conteneurImage img {
  width: 100%;
  height: auto;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="table.css" />
</head>

<body>
  <div id="grille">
    <div id="colonne">
      <div id="cellule">
        <div id="conteneurImage">
          <img src="home.png">
        </div>
        <div id="conteneurTexte">
          Accueil
        </div>
      </div>
    </div>
  </div>
  <script type="text/javascript">
  </script>
</body>

结果:

我的期望:

【问题讨论】:

  • 使用适合对象的属性
  • 只要使用max-height: 100%就可以了。

标签: javascript html css flexbox


【解决方案1】:

您可以在#conteneurImage 中使用“display: flex; justify-content: center;”。然后使用“width:auto;height:100%;”在#conteneurImage img。你可以在https://css-tricks.com/snippets/css/a-guide-to-flexbox/了解更多关于flex的信息

html {
  min-height: 100vh;
  position: relative;
}

body {
  height: 100vh;
  overflow: hidden;
}

#grille {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  flex-direction: row;
  display: flex;
  background-color: red;
}

#colonne {
  width: calc(100% / 3);
  height: 100%;
  background-color: green;
}

#cellule {
  flex-direction: column;
  width: 100%;
  height: calc(100% / 3);
  background-color: aqua;
}

#conteneurImage {
  width: 100%;
  height: 80%;
  background-color: violet;
  display:flex;
  justify-content: center;
}

#conteneurImage img {
  width: auto;
  height: 100%;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="table.css" />
</head>

<body>
  <div id="grille">
    <div id="colonne">
      <div id="cellule">
        <div id="conteneurImage">
          <img src="https://image.flaticon.com/icons/svg/2/2144.svg">
        </div>
        <div id="conteneurTexte">
          Accueil
        </div>
      </div>
    </div>
  </div>
  <script type="text/javascript">
  </script>
</body>

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 1970-01-01
    • 2016-05-16
    • 2014-09-19
    相关资源
    最近更新 更多