Html 如何在div中匹配图像图像大小是max-then-div还是min-then-div

Html 如何在div中匹配图像图像大小是max-then-div还是min-then-div,html,css,Html,Css,如何在div中匹配图像?图像大小可以是max-then-div或min-then-div html代码 <div class="main"> <img scr="image.jpg"> </div> 如何使用以下内容设置图像css: 图像高度100,宽度100 图像高度300和宽度300 您可以使用: img { max-width: 100%; height: auto; } // This would help you to automaticall

如何在div中匹配图像?图像大小可以是max-then-div或min-then-div

html代码

<div class="main">
  <img scr="image.jpg">
</div>
如何使用以下内容设置图像css:

  • 图像高度100,宽度100
  • 图像高度300和宽度300
  • 您可以使用:

    img { max-width: 100%; height: auto; } // This would help you to automatically fit the image.
    
    上面的css代码将帮助您处理大小大于div的图像。但不适用于小于div的图像。需要一点jQuery来实现您的目标,请在下面找到:

    $(document).ready(function(){
        imageWidth = $('.main img').width();
        parentWidth = $('.main').width();
        if (imageWidth > parentWidth) {
            $('.main img').css('width', '100%');
        }
    });
    
    当图像小于div时,它会根据您的要求调整自身大小并适合div


    因此,将css和脚本放置在这两种条件下工作。

    如果您的图像始终为方形,则只需添加
    img{
    宽度:200px;
    高度:200px;
    }

    若否,则

    .main {
        width: 200px;
        height: 200px;
        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }
    img {
        max-width: 200px;
        max-height: 200px;
        /* IE7 doesn't support display: table-cell property? so hack */
        *margin-top: expression((parentNode.offsetHeight.offsetHeight/2)-(parseInt(this.offsetHeight)/2) <0 ? "0" :(parentNode.offsetHeight/2)-(parseInt(this.offsetHeight)/2) +'px');     }
    
    .main{
    宽度:200px;
    高度:200px;
    文本对齐:居中;
    显示:表格单元格;
    垂直对齐:中间对齐;
    }
    img{
    最大宽度:200px;
    最大高度:200px;
    /*IE7不支持显示:表格单元格属性?所以hack*/
    
    *页边距顶部:表达式((parentNode.offsetHeight.offsetHeight/2)-(parseInt(this.offsetHeight)/2)在元素子元素“height:inherit”中使用该表达式,并且该元素将与伙伴的高度相同

    .main{
           height:200px;
           width:200px;
    }
    
    .img{
      height: inherit; //the imagem will be heigth 200px automatic
    }
    

    您应该根据DIV宽度或高度重新缩放图像,但这可能会降低图像质量。可以对
    使用单独的类/id,但内联足以轻松实现这一点
    .main{
           height:200px;
           width:200px;
    }
    
    .img{
      height: inherit; //the imagem will be heigth 200px automatic
    }