Resizing a background image via CSS

时光总嘲笑我的痴心妄想 提交于 2020-01-04 10:44:09

问题


I have this background image that is 175x175 but I am trying to make a "CD" cover out of it. In the code below (jsFiddle available), you will see it is not resized but merely "cropped". How do I fix this?

HTML:

<div class="cd"><div class="hole"></div></div>
<p>I want the image above to be resized to 75x75... but it's not</p>

<img src="http://userserve-ak.last.fm/serve/126/23679395.jpg" alt="Test" />
<p>Actual image size above.</p>

CSS:

.cd {
    -moz-border-radius: 63px;
    -webkit-border-radius: 63px;
    border-radius: 63px;
    background-image: url('http://userserve-ak.last.fm/serve/126/23679395.jpg');
    width: 75px;
    height: 75px;
    position: relative;
    border:1px solid #A1A1A1;
}
.cd .hole {
    width: 20px;
    height: 20px;
    position: absolute;
    background-color: #ddd;
    border:1px solid #A1A1A1;
    left: 28px;
    top: 28px;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
    border-radius: 15px;
}

回答1:


Use the background-size CSS property:

background-size: 75px 75px;

Alternatively:

background-size: 100% 100%;

There's also the shorthand background property:

background: url('http://userserve-ak.last.fm/serve/126/23679395.jpg') 100% 100%;



回答2:


Use background-size like here:

.cd {
    -moz-border-radius: 63px;
    -webkit-border-radius: 63px;
    border-radius: 63px;
    background-image: url('http://userserve-ak.last.fm/serve/126/23679395.jpg');
    background-size: 75px;
    width: 75px;
    height: 75px;
    position: relative;
    border:1px solid #A1A1A1;
}

Example: http://jsfiddle.net/5CDnw/6/




回答3:


Use background-size:cover it will fill the container whatever will be the size of container.

.cd {
    -moz-border-radius: 63px;
    -webkit-border-radius: 63px;
    border-radius: 63px;
    background-image: url('http://userserve-ak.last.fm/serve/126/23679395.jpg');
    background-size:cover;/*Add This*/
    -webkit-background-size: cover;/*Add This for webkit*/
    -moz-background-size: cover;/*Add This for mozilla*/
    -o-background-size: cover;/*Add This for opera*/
    width: 75px;
    height: 75px;
    position: relative;
    border:1px solid #A1A1A1;
}


来源:https://stackoverflow.com/questions/10991216/resizing-a-background-image-via-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!