请参阅此代码笔: https://codepen.io/allen-houng/pen/XGMjMr?editors=1100#0
<div> <img src="https://res.cloudinary.com/djcpf0lmv/image/upload/v1549372650/Templates/yoga.jpg" data-radium="true" style=";"> <div class="description"> Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum. </div> </div>
我有一个父 div 和两个子 div - 一个图像和一个描述。我根据视口高度调整图像大小,这意味着宽度将是动态的且响应灵敏。在没有 JavaScript 的情况下,如何调整相应同级 div .description
的大小以匹配图像的宽度?
换句话说,我该如何转变:
进入这个:
P粉0088297912024-04-07 09:39:14
您可以简单地将图像的宽度设置为 100%。只需添加“宽度:100%;”进入您的 img 样式标签进行测试,如下所示:
<div> <img src="https://res.cloudinary.com/djcpf0lmv/image/upload/v1549372650/Templates/yoga.jpg" data-radium="true" style="width: 100%;"> <div class="description"> Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum. </div> </div>
或者将其放入一个类中:
.img-full { display: block; width: 100%; }
<div> <img src="https://res.cloudinary.com/djcpf0lmv/image/upload/v1549372650/Templates/yoga.jpg" data-radium="true" class="img-full"> <div class="description"> Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum. </div> </div>
“display: block”只是确保您的 img 始终位于它自己的块中,无论宽度如何。即您的文字不会出现在其旁边,只会出现在其下方或上方。
P粉0304790542024-04-07 09:10:01
使容器inline-block
(或任何收缩到适合的配置,如table
、inline-grid
、inline -flex
、float
、absolute
等)然后强制文本宽度为 0
,从而定义容器的宽度通过图像(文本不影响宽度),然后使用 min-width
100%
.parent { background: pink; display:inline-block; } img { display: block; max-height: 70vh; } .description { width:0; min-width:100%; }
<div class="parent"> <img src="https://picsum.photos/id/1004/900/600"> <div class="description"> Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum. </div> </div>