我如何使用CSS创建圆角?
当前回答
没有“最好”的方法;有适合你的方法也有不适合你的方法。话虽如此,我在这里发布了一篇关于创建CSS+图像的流畅圆角技术的文章:
使用CSS和图像的圆角盒子-第2部分
这个技巧的概述是使用嵌套的div和背景图像重复和定位。对于固定宽度的布局(固定宽度可拉伸的高度),你需要三个div和三张图片。对于流体宽度布局(可拉伸宽度和高度),您需要9个div和9张图像。有些人可能会认为这太复杂了,但恕我直言,这是有史以来最简洁的解决方案。没有黑客,没有JavaScript。
其他回答
总有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;
}
如前所述,它有其局限性(圆角框后面的背景应该是普通的,否则角就不会与背景相匹配),但它适用于其他任何东西。
更新:通过使用精灵表改进了实现。
没有“最好”的方法;有适合你的方法也有不适合你的方法。话虽如此,我在这里发布了一篇关于创建CSS+图像的流畅圆角技术的文章:
使用CSS和图像的圆角盒子-第2部分
这个技巧的概述是使用嵌套的div和背景图像重复和定位。对于固定宽度的布局(固定宽度可拉伸的高度),你需要三个div和三张图片。对于流体宽度布局(可拉伸宽度和高度),您需要9个div和9张图像。有些人可能会认为这太复杂了,但恕我直言,这是有史以来最简洁的解决方案。没有黑客,没有JavaScript。
自从引入CSS3以来,使用CSS添加圆角的最好方法是使用border-radius属性。你可以阅读属性的规范,或者在MDN上获得一些有用的实现信息:
如果您使用的浏览器没有实现border-radius (Chrome pre-v4, Firefox pre-v4, IE8, Opera pre-v10.5, Safari pre-v5),那么下面的链接详细介绍了一大堆不同的方法。找一个适合你的网站和编码风格的,然后使用它。
CSS设计:创建自定义角 &边界 CSS圆角'Roundup' 25圆角技术与CSS
正如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文件
不要使用CSS, jQuery已经被提到过好几次了。如果你需要完全控制你的元素的背景和边界,可以试试jquery背景画布插件。它在背景中放置了一个HTML5 Canvas元素,并允许你绘制你想要的每个背景或边界。圆角,渐变等等。