Кнопки CSS

![]()
Мода на свои кнопки и элементы управления пошла уже давно. Раньше, в связи с бедностью CSS возможностей разработчики делали свои кнопки картинками. CSS кнопки сделанные картинками имеют кучу минусов. Например, они не отображаются при выключенных изображениях в браузере. Если же на кнопке написан сам текст кнопки, то дальнейшее производство таких кнопок превращается в тернистый путь. А представьте себе если надо поменять цветовую гамму или чуть изменить кнопку? Да, бывает, что разработчики все же умудяются сделать простую CSS кнопку, резиновую и без картинок. Но уверяю вас, что там одним DOM элементом не обходится.
Сегодня мы рассмотрим как можно сделать такие кнопки CSS.
В первом случае, способ с сайта с использованием дополнительного элемента, но с эффектом стекла. Который правда подойдет только для кнопок-ссылок (<a href=""></a>).
Второй же способ с сайта . Стиль, который можно применять как к <input> так и к <a>. Кнопочки там серенькие, они изображены на втором скриншоте. Кнопочки нимбупани соответственно на первом.
Способ нимбупани или "sexy buttons" использует дополнительный элемент <b>, а так же псевдоэлементы. За счет :before - тени, за счет :after - эффект стекла. А за счет дополнительного элемента <b> - тень от текста.
Давайте посмотрим на CSS код. Не волнуйтесь, ниже есть ссылка на демоверсию обоих примеров - сможете все посмотреть и понажимать.
.fancy_button {
display: inline-block;
position: relative;
padding: 0.25em 2em;
border: 1px solid;
border-color: transparent transparent rgba(202,202,202,0.27) transparent;
-webkit-border-radius: 7px; -moz-border-radius: 7px; border-radius: 7px;
-webkit-background-clip: padding-box;
}
.fancy_button b {
display: block;
z-index: 2; /* Necessary to make this top-most element */
position: relative;
text-shadow: rgba(0,0,0,0.45) 0 -1px 0;
}
.fancy_button:before,
.fancy_button:after {
position: absolute;
width: 100%;
height: 100%;
content: ""; /* Necessary to render these pseudo-elements */
display: block;
-webkit-background-clip: padding-box;
}
.fancy_button:before {
top: -4px;
left: -4px;
padding: 4px;
background: #086f14;
background: -webkit-gradient(linear, left top, left bottom, from(rgba(0,0,0,0.4)), to(rgba(77,77,77,0.4)));
background: -moz-linear-gradient(top, rgba(0,0,0,0.4), rgba(77,77,77,0.4));
-webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px;
}
.fancy_button:after {
top: -1px;
left: -1px;
border: 1px solid;
border-color: rgba(255,255,255,0.7) rgba(0,0,0,0.3) rgba(0,0,0,0.6) rgba(0,0,0,0.3);
-webkit-box-shadow: rgba(0,0,0,0.75) 0px 0px 3px; -moz-box-shadow: rgba(0,0,0,0.75) 0px 0px 3px; box-shadow: rgba(0,0,0,0.75) 0px 0px 3px;
-webkit-border-radius: 7px; -moz-border-radius: 7px; border-radius: 7px;
background: transparent -webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,0.6)), color-stop(0.5, rgba(255,255,255,0.15)), color-stop(0.5, rgba(255,255,255,0.01)), to(transparent));
background: transparent -moz-linear-gradient(top, rgba(255,255,255,0.6), rgba(255,255,255,0.15) 50%, rgba(255,255,255,0.01) 50%, transparent);
}
Думаю, здесь все понятно. Все достигается за счет CSS3 свойств. Border-radius, box-shadow, gradient и др. Получится кнопка как на картинке.
Способ сайта Цезарь Артс. Тут все немного интереснее. Во-первых способ позволяет использовать стиль как для ссылок так и для инпутов (кнопки и поля). Работает во всех современных браузерах. Для IE6 и подобных имеются даже костыли.
Посмотрим на код:
/* fixed IE */
input {
scrollbar-face-color: expression(runtimeStyle.scrollbarFaceColor = '#fff', className = (className) ? ' type-'+type : 'type-'+type)
}
input:focus,
input:active,
input:hover,
input.type-text,
input.type-search,
input.type-password,
input.type-file,
input.type-submit,
input.type-text:focus,
input.type-password:focus,
input.type-file:focus,
input.type-search:focus,
input.type-submit:focus {
outline:0;
outline-color: #f1f1f1;
border:1px solid #c7c7c7 !important;
}
/* /fixed IE */
input[type="text"], input[type="password"], input[type="file"], input[type="search"], input.type-text, input.type-password, input.type-file, input.type-search {
border:1px solid #c7c7c7 !important;
padding: 4px 5px;
height:16px;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
input[type="file"], input.type-file {
height:26px;
}
input[type="submit"], input.type-submit, .cabutton {
border:1px solid #c7c7c7 !important;
padding: 1px 7px 2px 7px;
background:#f0f0f0;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#EDEDED), color-stop(100%,#DDDDDF));
background: -moz-linear-gradient(top, #EDEDED 0%, #DDDDDF 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#EDEDED', endColorstr='#DDDDDF',GradientType=0 );
height:26px;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
box-shadow: inset 0 1px 0 #fff;
-moz-box-shadow: inset 0 1px 0 #fff;
-webkit-box-shadow: inset 0 1px 0 #fff;
text-shadow: 0 1px 0 #fff;
font-size: 13px;
}
.cabutton {
padding: 4px 7px 5px 7px;
}
input[type="submit"]:hover, input.type-submit:hover, .cabutton:hover {
border:1px solid #c7c7c7 !important;
background: #ddd;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#DDDDDF), color-stop(100%,#EDEDED));
background: -moz-linear-gradient(top, #DDDDDF 0%, #EDEDED 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#DDDDDF', endColorstr='#EDEDED',GradientType=0 );
}
Из костылей под IE6 тут используется следующее:
Так как IE6 не поддерживает ображение к типам полей (input[type="submit"]), то первый экспрешн добавляет к полю его тип в виде класса. Поэтому, когда описывается стиль дополнительно пишется input[type="submit"]:hover, input.type-submit:hover.
Второе - использование градиентов для IE<9 с помощью фильтров DX.
Как это все работает можно посмотреть в демо-версии.
Во втором примере две кнопки потому, что одна используется как <a>, а вторая как <input>.

(7 votes, average: 4,57 из 5)
4 Комментариев на «Кнопки CSS»
На демо ни IE8, ни Опера9.6 не отображают правильно :((
Ответить
makecode Ответил:
Июль 31st, 2011 at 21:18
Потому что это CSS3.
Ответить
А как же CSS3PIE?
Ответить
makecode Ответил:
Июль 31st, 2011 at 22:42
:) Верно подмечено. Попробуйте.
Ответить