html - 使图像适合div而不丢失CSS中的任何内容

标签 html css

我有一个包含两个图像的 div。我希望第二张图片适合 div,因为宽度和高度是动态的。

我的代码是这样的:

.box {
  width: 640px;
  height: 540px;
  float: left;
  overflow: hidden;
}

.img-border {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 20px;
  margin: 5px;
}
<div class="box" id="target">
  <div align="center">
    <img src="http://cdn.tgdd.vn/Files/2014/06/24/551004/game-duoi-hinh-bat-chu4.jpg" width="60%" height="60%">
  </div>
  <img class="img-border" id="imgQues" src="https://4.bp.blogspot.com/-K5SwATiq6cI/U84bk7MZPWI/AAAAAAAADkI/4lWV0ErVAFs/s1600/2014-07-22+14.11.00-1.png" />
  <div class="comment" id="chatbox">
  </div>
</div>

您在 .img-border 中看到的问题是不适合(拉伸(stretch)和调整大小)到 .box div 中并保持其纵横比。

有什么方法可以让第二张图片 img-border 适合 div 并保持比例吗?

最佳答案

尝试以下操作:

.box {
  width: 640px;
  height: 540px;
  float: left;
  overflow: hidden;
  /**
    Just for visualization 
  **/
  background: gray;
}

/**
  Just dummy names, rename as you like
*/
.box__first-child,
.box__second-child {
  float: left;
  width: 49.99999999%;
}

/**
  Force images to always take remaining space
*/
.box img {
  width: 100%;
}

.img-border {
  width: 100%;
  height: 100%;
  display: block;
  border-radius: 20px;
  margin: 5px;
}
<div class="box" id="target">
  <div class="box__first-child" align="center">
    <img src="http://cdn.tgdd.vn/Files/2014/06/24/551004/game-duoi-hinh-bat-chu4.jpg" width="60%" height="60%">
  </div>
  <div class="box__second-child">
    <img class="img-border" id="imgQues" src="https://4.bp.blogspot.com/-K5SwATiq6cI/U84bk7MZPWI/AAAAAAAADkI/4lWV0ErVAFs/s1600/2014-07-22+14.11.00-1.png" />
    <div class="comment" id="chatbox">
    </div>
  </div>
</div>

html 更改不是强制性的,您也可以通过其他方式进行更改,但这对我来说似乎是最干净的。诀窍基本上是强制图像始终占据整个空间并使用 float 对齐元素。

编辑:

Preview Variant 1

jsfiddle - variant 1

Preview Variant 2

jsfiddle - variant 2

关于html - 使图像适合div而不丢失CSS中的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52345405/

相关文章:

html - Div inside 按钮在 IE 中无法正常工作

html - 为html制作一个颜色可变的图像?

Javascript 代码有时只运行

html - <source> "sizes"属性在 Chrome 中对 <picture> 元素有效吗?

接受输入、运行 R 代码并将结果返回给 HTML 的 HTML 页面

jquery - 将 html 保存在 cookie 中

javascript - 浏览器间标签交易

html - Firefox (3.6.3 Mac) 无法向左浮动一组左浮动列表项中的最后一个

javascript - 如何消除引导输入元素内的间隙?

javascript - 功能不适用于 innerhtml