gpt4 book ai didi

javascript - 保持图像宽高比并在 div 内

转载 作者:行者123 更新时间:2023-11-28 01:03:38 28 4
gpt4 key购买 nike

我想在 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>

结果:

the result

我的期望:

what I expect

最佳答案

您可以在#conteneurImage 中使用“display: flex; justify-content: center;”。然后使用“宽度:自动;高度: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>

关于javascript - 保持图像宽高比并在 div 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52515243/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com