【问题标题】:Can HTML or CSS give a cropped effect to image?HTML 或 CSS 可以给图像带来裁剪效果吗?
【发布时间】:2011-06-17 23:30:26
【问题描述】:

我并没有尝试实际裁剪图像文件。图像周围有一个粗边框,我只想以某种方式隐藏它。标记html是这样的。

<div class="imgDiv">
    <img height="200" width="200" src="http://site.com/image.jpg">
</div>

有没有办法使这个图像居中或调整大小以使边框消失?

【问题讨论】:

    标签: html image crop


    【解决方案1】:

    假设您的图像上有 10 像素的令人讨厌的边框。以下 CSS 会将其隐藏起来:

    .imgDiv { width:180px; height:180px; overflow:hidden; }
    .imgDiv img { display:block; margin:-10px 0 0 -10px; }
    

    另一种方法是使用位置:

    .imgDiv { width:180px; height:180px; overflow:hidden; }
    .imgDiv img { position:relative; top:-10px; left:-10px; }
    

    【讨论】:

    • 那只会删除顶部和左侧部分。
    • 你是对的,高度和宽度应该是180px(而不是190px)。显然,当我在写这篇文章时,我在心里交换了示例大小。我已更新我的答案以反映正确的宽度和高度。
    【解决方案2】:

    当然。假设您只想要中心 100x100。你可以使用这个 CSS:

    .imgDiv {
        width: 100px;
        height: 100px;
        overflow: hidden;
    }
    .imgDiv > img {
        position: relative;
        left: -50px;
        top: -50px;
    }
    

    在这里,我使用这种技术获得了 128x128 头像的中心 64x64:http://jsfiddle.net/5kHbQ/

    【讨论】:

    • 非常感谢。我喜欢这种方式。
    【解决方案3】:

    虽然不是使用它们的主要目的,但您可以使用CSS Sprites 删除边框。

    本质上,您将使用div 元素定义为图像所需的高度和宽度。

    然后,您可以将background-image 属性设置为图像的 url(这里要注意,图像的 url 是相对于 CSS 的位置的,所以请注意,如果您使用外部 CSS 文件代替内联 style 属性)。

    最后,您将设置background-position 属性以偏移图像,使其与您定义为“框架”的div 元素对齐。

    【讨论】:

      【解决方案4】:

      你可以用 css 来做,内联:

      <div class="imgDiv" style="width:200px;height:200px;background:url(http://site.com/image.jpg) no-repeat -20px -20px;"></div>
      

      或在css中:

      .imgDiv{
        width:200px;
        height:200px;
        background:url(http://site.com/image.jpg) no-repeat -20px -20px;
      }
      

      无论哪种方式,您都将删除 html 中的 &lt;img&gt; 节点。

      使用背景的宽度、高度和最后两个值。

      【讨论】:

        猜你喜欢
        • 2015-12-08
        • 2013-12-22
        • 1970-01-01
        • 2012-09-29
        • 2016-09-24
        • 2016-11-28
        • 2014-11-30
        • 2018-08-07
        • 2016-04-13
        相关资源
        最近更新 更多