gpt4 book ai didi

html - 如何使用隐式子元素的宽度覆盖父元素的宽度?

转载 作者:可可西里 更新时间:2023-11-01 13:31:41 25 4
gpt4 key购买 nike

我想将 div 元素的宽度指定为其中包含的子 img 元素的宽度。但是,这个宽度是隐式的,具体取决于源图像的大小。

第一个 flex 元素显示了我试图达到的效果,但是,我必须手动将宽度值设置为 150px。如何动态实现(最好不用 javascript)?

<!DOCTYPE html>
<html>
<head>
<style>
.flex-item {
border: 1px solid #30b0b0;
color: #303030;
text-align: center;
padding: 5px;
}

.flex-container {
border: 1px solid #30b0b0;
display: flex;
justify-content: space-around;
list-style: outside none none;
padding: 5px;
}
</style>
</head>
<body>
<ul class="flex-container">
<li class="flex-item">
<div style="width: 150px; margin: auto;">
<img height="100px" src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Metrostation_Mladost_1.JPG/150px-Metrostation_Mladost_1.JPG">
<p>This text stays within the image</p>
</div>
</li>
<li class="flex-item">
<div>
<img height="100px" src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Metrostation_Mladost_1.JPG/150px-Metrostation_Mladost_1.JPG">
<p>This text sticks out further than the image</p>
</div>
</li>
</ul>
</body>
</html>

最佳答案

我想制作图像容器 display: table 并为标题提供样式 display: table-cell; caption-side: bottom 应该可以解决问题。

请注意,我从这个答案中得到了一些帮助: Image caption width to same as image

我相信这是您正在寻找的图像标题功能!

<!DOCTYPE html>
<html>
<head>
<style>
.flex-item {
border: 1px solid #30b0b0;
color: #303030;
text-align: center;
padding: 5px;
}

.flex-container {
border: 1px solid #30b0b0;
display: flex;
justify-content: space-around;
list-style: outside none none;
padding: 5px;
}

.image-group-container {
display: table;
}

.caption {
display: table-caption;
caption-side: bottom;
}
</style>
</head>
<body>
<ul class="flex-container">
<li class="flex-item">
<div style="width: 150px; margin: auto;">
<img height="100px" src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Metrostation_Mladost_1.JPG/150px-Metrostation_Mladost_1.JPG">
<p>This is in a div with a hard-coded width, so it stays in the proper boundaries.</p>
</div>
</li>
<li class="flex-item">
<div class="image-group-container">
<img height="100px" src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Metrostation_Mladost_1.JPG/150px-Metrostation_Mladost_1.JPG">
<p class="caption">This text also stays within image without hard-coding the width.</p>
</div>
</li>
</ul>
</body>
</html>

关于html - 如何使用隐式子元素的宽度覆盖父元素的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544462/

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