按钮如何使用外部css样式
1、首先新建btn.css样式文件
将默认的button样式去除/**
* Reset button styles.
* It takes a bit of work to achieve a neutral look.
*/
button {
padding: 0;
border: none;
font: inherit;
color: inherit;
background-color: transparent;
/* show a hand cursor on hover; some argue that we
should keep the default arrow cursor for buttons */
cursor: pointer;
}
完成后标签显示如普通文本
button
(相关课程推荐:css视频教程)
2、自定义按钮样式
我们上面已经移除了默认样式,现在我们来定义自己的button样式
①“button”样式可以被用于link或是button
② 让样式变的可供选择,毕竟页面会存在各种各样的样式
使用class选择符 .btn (类似bootstrap中的使用).btn {
/* 默认为button 但是在上依然有效 */
display: inline-block;
text-align: center;
text-decoration: none;
/* 创造上下间距一定的空间 */
margin: 2px 0;
/* border透明 (当鼠标悬停时上色) */
border: solid 1px transparent;
border-radius: 4px;
/* padding大小与字体大小相关 (no width/height) */
padding: 0.5em 1em;
/* 确保字体颜色和背景色有足够区分度! */
color: #ffffff;
background-color: #9555af;
}
高对比度! strong contrast (5.00):
3、对button的hover,focus,active状态进行区分
由于button是一个需要交互的标签,用户在对button进行操作时肯定要得到反馈
浏览器本身对focus和active有默认的样式,但是我们的重置取消了这部分样式;因此我们需要添加一部分css代码完成这部分的操作,并让button变化的状态和我们此前的样式更搭!
①:active状态/* old-school "的button位置下移+ 颜色饱和度增加 */
.btn:active {
transform: translateY(1px);
filter: saturate(150%);
}
②我们可以改变按钮的颜色,但是我想为悬停时保留这种样式:/* 鼠标悬停时颜色反转 */
.btn:hover {
color: #9555af;
border-color: currentColor;
background-color: white;
}
③让我们增加focus样式,用户经常会用键盘或是虚拟键盘(ios或安卓等)来focus表单,button,links和其他一些交互性组件
一方面:这样可以加快交互效率
另一方面:对有的人而言,无法使用鼠标,那么就可能依赖键盘或是其他工具访问网站
在绝大多数我见过的项目中,设计师仅仅指定mouse-over样式而没有focus样式,我们应该怎么做呢?
答案:最简单的方法就是复用hover样式给focus/* 复用样式 */
.btn:hover,
.btn:focus {
color: #9555af;
border-color: currentColor;
background-color: white;
}
④如果要用到focus样式,那么就需要移除浏览器button默认的样式(否则当button是focus或active状态下都会有outline边框).btn {
/* ... */
/* all browsers: 移除默认focus样式 */
outline: none;
}
/* Firefox: 移除默认focus样式 */
.btn::-moz-focus-inner {
border: none;
}
试一试效果,如果有键盘可以尝试用tab和shift+tab进行导航从而触发focus!
4、在html页面中引入btn.css文件并使用
本文来自css答疑栏目,欢迎学习!