【问题标题】:CSS How to make DIV Border Dynamic in WidthCSS如何使DIV边框宽度动态
【发布时间】:2014-01-29 08:17:43
【问题描述】:

我在 HTML 控件中水平显示图像。图像表位于主 DIV 内。 DIV 的 CSS 如下:

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

问题是主 DIV 边框没有延伸,图像从它上面掉出来,如下图所示:

这是 HTML 代码:

<body>
<div id="main">

    ...

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

    ...

</body>

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

【问题讨论】:

  • 您不应该将表格元素用于图像列表。考虑制作 ul/li 而不是 table/tr。如果您需要表格显示,请使用 display: table-cell。

标签: html css image html-table


【解决方案1】:

您遇到的问题 - 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%;
}

【讨论】:

  • @NidaSulheri 它们会按比例缩放,我没有在img 标签上分配任何固定的width
  • 水平滚动条永远不会出现,它会挤压图片以适应页面:(
  • @NidaSulheri 所以你想让水平滚动条出现?
  • 是的......当图像落在 DIV 之外时,它就会出现。我想要: 1. DIV 边框应该相对于其中的图像扩展自身,而不是压缩图像以适应可见的页面布局。 2. 因此,当图像超过页面的可见部分时,它应该添加水平滚动条。
  • 这似乎有效。另外,这个 sn-p 也解决了我的问题:#main { width: 100%;高度:自动;边距:自动;填充:2px 0px 0px 0px;边框:1px 实心#ccc;显示:表格;向左飘浮;但是,我将您的答案标记为正确。感谢您的努力:)
【解决方案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

【讨论】:

  • 我猜他们认为您复制了解决方案,可能是这样吗?虽然不是downvoter...
  • @Era : 伙计...我欠你很多时间...我们是新朋友! :D
  • 这似乎不对,因为它在添加更多图片时会挤压图片。它不会扩展控件宽度...我想要的是扩展控件水平宽度和添加更多图片的边框...不压缩已经上传的图片...
  • 感谢您标记朋友.. :) 我们是邻居 Mr.Alien .. 吗?
【解决方案3】:

将此 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??
  • #main { 宽度:自动;高度:自动;边距:自动;填充:2px 0px 0px 0px;边框:3px 实心#ccc; } #main table img{width:500px;height:500px}
猜你喜欢
  • 1970-01-01
  • 2020-10-28
  • 2013-09-13
  • 2010-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
相关资源
最近更新 更多