【问题标题】:How to control with CSS width of images parent element如何使用 CSS 控制图像父元素的宽度
【发布时间】:2013-03-10 12:43:22
【问题描述】:

在流畅的设计布局中,我想缩放图像,使它们都具有相同的高度,但可以根据图像纵横比具有不同的宽度。此外,所有图像都位于锚标记内。在 Mozilla 浏览器中,我遇到一个问题,即锚标记的宽度不会自动调整。例如,如果图像的尺寸为 200x100 像素,锚标签的高度为 50 像素,那么在 Mozilla 中,锚标签的尺寸为 200x50 像素,而不是我想要的 100x50 像素。为了解决这个问题,我的 CSS 应该是什么?谢谢

我的 HTML 是:

<a class="testimage"><img src="sliderimages/picture8.jpg"/></a>

CSS 是:

<style>  
    .testimage {height:10%;display:inline-block;border:1px solid yellow;}
    .testimage img {height:100%;}
</style>

【问题讨论】:

  • 你能在jsfiddle中加入一个例子吗?
  • 请在此处也张贴图片..(或其他任何图片相同的比例)

标签: css width fluid-layout


【解决方案1】:

您需要使用 JavaScript 进行一些简单的计算。这是一个带有 JavaScript 的简单 HTML 页面,供您修改和测试。

<!DOCTYPE html>
<html>
<head>
    <title>
        Set Image Height
    </title>
</head>

<body>
    <img src='testimage1.jpg' onload='setImageHeight()'>
    <img src='testimage2.png' onload='setImageHeight()'>

    <script>
        function setImageHeight(event) {
            // Allow for cross-platform differences
            event = event || this.event;
            element = event.target || event.srcElement;

            var temp = new Image(),
                fixedHeight = 50,
                height, width, scaledWidth;

            temp.src = element.src;
            width = temp.width;
            height = temp.height;
            scaledWidth = width * fixedHeight / height;

            element.style.width = scaledWidth + "px";
            element.style.height = fixedHeight + "px";
        }
    </script>
</body>
</html>

这是example

【讨论】:

  • 嗨詹姆斯,我想弄清楚如何在 CSS 中做到这一点。在这种情况下,Javascript 不是一个选项
  • CSS 不是编程语言。它不允许您进行任何计算。我可以想到三个替代方案。 (1) 您根据每个图像的尺寸手动滚动 CSS (2) 您使用 PHP 或其他一些服务器端代码动态生成 CSS 样式声明 (3) 您生成(缩略图)图像以显示在飞,使它们已经是您希望它们出现的大小。
【解决方案2】:

试试这个.... 将 .testimage 设置为 display: block; 要指定标签的高度或宽度,您应该将显示应用于块而不是内联块。 希望这行得通。

【讨论】:

    猜你喜欢
    • 2011-12-29
    • 2013-12-07
    • 2015-04-17
    • 1970-01-01
    • 2020-01-17
    • 2018-11-15
    • 2016-08-18
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多