CSS如何使DIV边框的宽度动态化

3

我正在水平地在HTML控件中展示图片。图片的表格位于主DIV内。DIV的CSS如下:

#main
{
    width: auto;
    height: auto;
    margin: auto;
    padding: 2px 0px 0px 0px;
    border: 3px solid #ccc; 
}

问题在于主DIV边框没有扩展,图片会脱离它,如下截图所示:
enter image description here
这是HTML片段:
<body>
<div id="main">

    ...

    <table>
        <tr id="image-list">
        </tr>
    </table>

    ...

</body>

请建议如何修改代码,使DIV边框根据其中的图像自动增加其宽度?

在图像列表中,不应该使用表元素。请考虑使用 ul/li 代替 table/tr。如果需要表格显示,则使用 display: table-cell。 - enguerranws
3个回答

3
您遇到的问题是-Demo

以下方法可解决此问题,我没有使用任何花哨的方法,只是将width: 100%;分配给table元素,然后使用table-layout: fixed;,这里非常重要,然后只需为您的img标签使用max-width: 100%;...还要确保您也为td元素使用width...

Demo(已修复问题)

#main {
    width: auto;
    height: auto;
    margin: auto;
    padding: 2px 0px 0px 0px;
    border: 3px solid #ccc; 
}

img {
    outline: 1px solid #eee;
}

table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

table tr td {
    width: 33%;
}

table tr td img {
    max-width: 100%;
}

@NidaSulheri 它们将按比例缩放,我没有在 img 标签上分配任何固定的 width - Mr. Alien
水平滚动条从未出现,它会压缩图片以适应页面 :( - Azeem
@NidaSulheri,所以您想让水平滚动条出现吗? - Mr. Alien
是的...当图像超出DIV时,它会出现。我想要:1. DIV边框应该根据其中的图像自动扩展,而不是压缩图像以适应可见页面布局。2.因此,当图像超出页面的可见部分时,应添加水平滚动条。 - Azeem
@NidaSulheri 在这之前你应该告诉我 :) 这是链接 - http://jsfiddle.net/9xp6G/2/ - Mr. Alien
1
看起来这个代码段正在工作。此外,这个片段也解决了我的问题: #main { width: 100%; height: auto; margin: auto; padding: 2px 0px 0px 0px; border: 1px solid #ccc; display:table; float: left; } 不过,我会把你的答案标记为正确的。感谢你的努力 :) - Azeem

2

给:

table{width:100%;}

以及

#main
{
width: 100%; /*not auto*/
 /*remaining css */
}

that would solve your problem

so, final css :

html, body {
    width:100%; /* important */
    height:100%; /* important */
    margin:0;
    padding:0;
}
#main {
    width: 100%; /* changed*/
    height: auto;
    padding: 2px 0px 0px 0px;
    border: 3px solid #ccc;
}
table{
    width:100%; /* changed*/
    height:auto;
    border-collapse: collapse; /* added and very important*/
    table-layout: fixed;/* added and very important*/
}
img{
    width:auto; /* change as per your need */
    max-width: 100%;
    height:auto; /* important to maintain aspect ratio of images */
}

你的问题

解决方案演示


我猜他们认为你抄袭了解决方案,所以可能是这样?虽然不是那个投票者... - Mr. Alien
@Era:伙计...我欠你好大的一个人情...我们成了新的最好的朋友!! :D - NoobEditor
这似乎不正确,因为它在添加更多图片时会压缩图片。它不会扩展控件的宽度...我想要的是在添加更多图片时扩展控件的水平宽度和边框...而不是压缩已上传的图片... - Azeem
感谢标记朋友们.. :) 我们是邻居吗,外星人先生..? - Richa

-1
将以下 CSS 代码添加到您的样式表中以解决该问题:
#main
{
    width: 400px /*you can give fixed value or auto value*/;
    height: auto;
    margin: auto;
    padding: 2px 0px 0px 0px;
    border: 3px solid #ccc; 
}
#main table
{
    width:100%;
}

如果图片是 500 x 500 px 呢? - NoobEditor
#main { 宽度:自动; 高度:自动; 边距:自动; 填充:2像素0像素0像素0像素; 边框:3像素实线 #ccc; } #main table img{宽度:500像素;高度:500像素} - Krish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接