我如何使用CSS创建圆角?
当前回答
总有JavaScript的方式(见其他答案),但因为它是纯粹的样式,我有点反对使用客户端脚本来实现这一点。
我更喜欢的方式(虽然它有其局限性),是使用4圆角图像,你将定位在你的盒子的4个角使用CSS:
<div class="Rounded">
<!-- content -->
<div class="RoundedCorner RoundedCorner-TopLeft"></div>
<div class="RoundedCorner RoundedCorner-TopRight"></div>
<div class="RoundedCorner RoundedCorner-BottomRight"></div>
<div class="RoundedCorner RoundedCorner-BottomLeft"></div>
</div>
/********************************
* Rounded styling
********************************/
.Rounded {
position: relative;
}
.Rounded .RoundedCorner {
position: absolute;
background-image: url('SpriteSheet.png');
background-repeat: no-repeat;
overflow: hidden;
/* Size of the rounded corner images */
height: 5px;
width: 5px;
}
.Rounded .RoundedCorner-TopLeft {
top: 0;
left: 0;
/* No background position change (or maybe depending on your sprite sheet) */
}
.Rounded .RoundedCorner-TopRight {
top: 0;
right: 0;
/* Move the sprite sheet to show the appropriate image */
background-position: -5px 0;
}
/* Hack for IE6 */
* html .Rounded .RoundedCorner-TopRight {
right: -1px;
}
.Rounded .RoundedCorner-BottomLeft {
bottom: 0;
left: 0;
/* Move the sprite sheet to show the appropriate image */
background-position: 0 -5px;
}
/* Hack for IE6 */
* html .Rounded .RoundedCorner-BottomLeft {
bottom: -20px;
}
.Rounded .RoundedCorner-BottomRight {
bottom: 0;
right: 0;
/* Move the sprite sheet to show the appropriate image */
background-position: -5px -5px;
}
/* Hack for IE6 */
* html .Rounded .RoundedCorner-BottomRight {
bottom: -20px;
right: -1px;
}
如前所述,它有其局限性(圆角框后面的背景应该是普通的,否则角就不会与背景相匹配),但它适用于其他任何东西。
更新:通过使用精灵表改进了实现。
其他回答
jQuery是我个人处理这个问题的方法。css的支持是最低限度的,图像太精细,能够选择你想在jQuery圆角的元素对我来说是完美的,即使有些人会毫无疑问地反对。这里有一个我最近在工作项目中使用的插件:http://web.archive.org/web/20111120191231/http://plugins.jquery.com:80/project/jquery-roundcorners-canvas
如果你要使用边界-半径解决方案,有一个很棒的网站可以生成css,使它适用于safari/chrome/FF。
无论如何,我认为你的设计不应该依赖于圆角,如果你看看Twitter,他们只是对IE和opera用户说F****。圆角是一个很好的选择,我个人认为这是为那些不使用IE的酷用户保留的:)。
当然,这不是客户的意见。 链接如下:http://border-radius.com/
正如Brajeshwar所说:使用border-radius css3选择器。现在,您可以分别为基于Mozilla和Webkit的浏览器应用-moz-border-radius和-webkit-border-radius。
那么,ie浏览器会发生什么呢?微软有许多行为使ie浏览器有一些额外的功能,并获得更多的技能。
这里:一个.htc行为文件,用于从CSS中的border-radius值获取圆角。为例。
div.box {
background-color: yellow;
border: 1px solid red;
border-radius: 5px;
behavior: url(corners.htc);
}
当然,行为选择器不是一个有效的选择器,但你可以把它放在一个不同的css文件与条件注释(仅适用于IE)。
行为HTC文件
要让圆角发挥作用是多么复杂,甚至雅虎都不鼓励他们(见第一个项目符号)!当然,他们在那篇文章中只谈论了1像素的圆角,但有趣的是,即使是一家拥有他们专业知识的公司也得出结论,让他们大部分时间工作太痛苦了。
如果你的设计可以在没有它们的情况下存活,这就是最简单的解决方案。
随着对CSS3的支持在Firefox、Safari和Chrome的新版本中实现,看看“边界半径”也会有帮助。
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
像任何其他CSS简写一样,上面也可以用扩展格式编写,从而实现左上角、右下角等不同的边界半径。
-moz-border-radius-topleft: 10px;
-moz-border-radius-topright: 7px;
-moz-border-radius-bottomleft: 5px;
-moz-border-radius-bottomright: 3px;
-webkit-border-top-right-radius: 10px;
-webkit-border-top-left-radius: 7px;
-webkit-border-bottom-left-radius: 5px;
-webkit-border-bottom-right-radius: 3px;