首页 文章

圆形掩模使用图像本身和纯CSS的图像

提问于
浏览
1

我实际上想知道是否可以使用单个伪元素将图像屏蔽为圆形,这是图像本身?让我们说它是一个矩形图像(不是正方形),你想让它被掩盖成圆形,而不会挤压图像?

所以你有:

HTML

<img src="#" class="mask">

CSS

.mask {
  A lot of CSS possibilities, up to you
}

我知道,使用父div并使用 overflow:hiddenborder-radius:50% 它是可能的,但你可以不使用第二个伪元素吗?

更新!

我只是在寻找CSS代码 border-radius:50% 来创建圆形形状,但事实并非如此 . 图像应该变成圆形而不是椭圆形 . 您可以简单地使用 widthheight 彼此相等,但随后图像会被挤压 . The answer should contain a none-squeezed image result

The requirement of the solution

  • 图像应该是一个完美的圆形,而不是椭圆形
  • 无论原始宽高比如何,都不应挤压图像 . 即使你只看到中间部分为圆形,其余部分隐藏 .

2 回答

  • 0

    如果你只能使用img标签来生成一个掩码,那么我能想到的唯一解决方法是: DEMO

    .mask {
        width: 0px;
        height: 0px;
        border-radius: 100%;
        background:url(http://placehold.it/300x400) center;/* define position to choose clipped area */
        padding:50px;/* this makes a 100px square, so a perfect circle can be made with border-radius */
    }
    

    如果你可以使用包装器,它可以保持图像和掩码使用的原始空间可以通过coordonates在它的顶部任何地方 . DEMO

    标记:

    <div class="mask r150 top100 left150">
        <img src="http://placehold.it/300x400" />
    </div>
    

    CSS:

    .mask {
        position:relative;
        overflow:hidden;
        display:inline-block;/* preserve display behavior of initila image to mask*/
        box-shadow:0 0 0 1px;/* show where i stands */
    }
    .mask img {
        display:block;/* a way to remove bottom gap*/
    }
    .mask:before {
        content:'';
        position:absolute;
        border-radius:100%;
        box-shadow:0 0 0 2000px white;
    }
    .r150:before {
        height:150px;
        width:150px;
    }
    .top100:before {
        top:100px; 
    }
    .left150:before {
        left:150px;
    }
    

    使用额外的类可以帮助您调整不同的大小和掩码位置 .

  • 1

    这里 Fiddlehttp://jsfiddle.net/8CuXQ/

    像这样的东西:

    .mask {
        width: 300px;
        height: 300px;
        border-radius: 150px;
        -webkit-border-radius: 150px;
        -moz-border-radius: 150px;
    }
    

相关问题