【问题标题】:div style height not workingdiv样式高度不起作用
【发布时间】:2014-10-26 22:08:19
【问题描述】:

我需要直接在 html 中设置 div 的大小,但我有一个问题。 div 容器大小仅在我设置 CSS 类中的高度样式时才有效,否则容器将没有任何高度(即使在 div 标记中设置样式,我正在尝试做)。

宽度和高度是从图片中获取的,我不知道有什么其他方法可以做到这一点;

list($width, $height) = getimagesize('dir/to/img.jpg');
echo $width . $height; //WORKING

// resizing the img...
// the resizing script have max width and height
$img_width = 'width="' . $width . '"';
$img_height = 'height="' . $height . '"';

<div class="img_container" ' . $img_width . ' ' . $img_height . '>
    <img src="'. $img_dir . '" class="img"/>
</div>

// the html output is ok but maybe it's not overwriting the css

这是我用于容器的 css 类:

.img_container {
    overflow: hidden;
    position: relative;
    box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.05);
    display: block;
    width: auto;
    min-height: 50px;
    max-height: auto;
}
.img {
    height: auto;
    display: block;
}

如果我从.img_container 中删除高度,则 div 将没有任何高度(并且图像未显示,但 div 具有宽度和高度)。

所以我想要的是 div 具有与图像相同的宽度和高度。

【问题讨论】:

  • 首先,在height: auto后面插入分号会发生什么?
  • html 是什么样子的,您是否有任何额外的 css(如绝对定位...)用于图像?
  • 您根本没有设置 div 的高度。只是输出一些像素值,甚至没有 div 标签的任何属性(正如你所做的那样)不会做任何事情。也许重新访问您选择的 HTML/CSS 指南?
  • 对不起,我写了这两个选项。是的,我有位置:图像中的绝对位置和容器中的相对位置。
  • 我没说,属性已经在变量里了。我刚刚编辑过。

标签: php css html


【解决方案1】:

内联样式应该覆盖(优先级高于)外部 CSS,但您没有正确设置宽度和高度。您应该像这样使用style 属性;

<div class="img_container" style="width: <?php echo $width; ?>px; height: <?php echo $height; ?>px;">

您还需要重新输入 PHP 解析才能使用 PHP 变量(使用上面的 &lt;?php ?&gt; 标签)。

此外,您的 CSS 中有一个错误,因为您没有在 img 规则的末尾添加分号 (;)。

【讨论】:

  • 对不起,我应该这么说的。变量已经包含它: $img_width = 'width="' . $width . '"';
  • 啊,是的。使用 width=height= 不会覆盖 CSS,并且会被贬值。
  • style="width/height" 会起作用吗?还是一样?
  • 我已经更新了我的答案。您应该只使用来自getimagesize 函数的原始数字,然后放入style= 参数中。
  • 谢谢,问题是我没有写 "px": $img_width = 'width: ' 。 $宽度。 'px;';但现在它起作用了!
【解决方案2】:

我发现 height:auto 在获取 div 中的内容方面为我工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多