在HTML中指定图像的宽度和高度

时间:2014-12-08 14:12:46

标签: jquery html css

所以我正在使用一个名为slick.js的响应式轮播插件,但如果我在HTML中指定图像的宽度和高度,则响应方面不起作用(随着页面变小,照片的宽度减少,但高度保持不变,所以他们看起来非常紧张)。

我最初只是没有在HTML中指定维度,但显然它没有验证,我知道这是不好的做法。

知道如何绕过这个吗?

如有必要会提供代码,但我觉得这可能只是一个问题我可以在没有代码的情况下给出答案。

2 个答案:

答案 0 :(得分:2)

为了避免那种可怕的外观或拉伸,请这样做。

1.将图像包装在容器中。见下文。

<div id="imager"><!-- Begin -->

<!-- Your image goes here -->

</div><!-- End Imager -->

2.为 #imager 创建一个CSS块,并定义宽度和高度。

 #imager {
    wdth: 400px; /* Adjust as need */
    height: 350px; /* Adjust as need */
    overflow: hidden; /* hides any part of the image that grows 
    beyond the given dimension */
    }

3.为图像本身创建一个CSS块使用eighter将高度或宽度设置为auto。

 #imager img {
        wdth: 100%; /* Must match the width of #imager */**
        height: auto;/* Auto allows the image 
        the space to adjust without deteriorating */
        }

答案 1 :(得分:0)

您可以通过在页面的任何一个头部或可能在外部样式表中定义CSS中'img'的值来否决slick.js - 您可能必须考虑哪个规则(slick.js或CSS)是最后要渲染。

直接在img元素上指定尺寸并不是很好的做法并且会验证 - 但是你只能使用'无单位值'指定比例'fx'宽度:600' - HTML中'img'的比例与值类似百分比,像素或任何其他值都不会起作用。然而,“无单位值”仍然是指以像素为单位测量的图像比例。

这是因为元素'img'属于称为'替换元素'的元素组,它带有预定义的样式 - 在'img'的情况下,原始图像的比例将被保留,直到某些东西else在CSS中定义为“真实”值:

使用CSS2,您可以通过向元素添加类来轻松缩放图像:

.img_width {
    width: 100%; 
    height: auto; 
}

使用CSS3 - 缺少IE8及之前的支持 - 您有2个机会可以直接在元素上应用:

使用背景大小'封面':

img  {
    background: url(image.jpg);
    background-repeat: no-repeat;
    background-position: center; 
    background-size: cover; 
]

使用background-size'contains':

img  {
    background: url(image.jpg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain; 
}
相关问题