CSS如何使DIV边框动态宽度

时间:2014-01-10 11:17:43

标签: html css image html-table

我正在水平显示HTML控件中的图像。图像TABLE在主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边框根据其中的图像自动增加其宽度?

3 个答案:

答案 0 :(得分:3)

您遇到的问题 - Demo

这就是解决问题的方法,我没有做任何想象,我将width: 100%;分配给table元素,而不是使用重要的table-layout: fixed; 在这里,而不仅仅是max-width: 100%;用于img标记...还要确保对width元素使用td ...

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%;
}

答案 1 :(得分:2)

给:

table{width:100%;}

以及

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

可以解决您的问题

所以,最后的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 */
}

your problem

solution demo

答案 2 :(得分:-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%;
}