At the start of the book, we took a look at how you can use variables to assign values in your CSS styling; the observant among you may have spotted something: we were using some basic operators to create colors. In this recipe we're going to extend this principle and use it to style one of the most important components of any website—the humble button! Normally, you would specify styles either using a selector ID or a class. While it will work, it will make things harder when updating or changing styles. Less can really help here; in this exercise we're going to create a base button, using the color function. We'll also look at how to alter the fill-in and border colors used at the same time, by altering the base color.
test less operators.html
:<body> <form action="demo_form.php"> Username: <input type="text" name="usrname" /><br /> <input type="submit" value="Submit" /> </form> </body>
coloroperators.css
:body { padding: 20px; } @color-button: #d24444; input.submit { color:#fff; background:@color-button; border: 1px solid @color-button - #222; padding:5px 12px; }
In this exercise we've used a simple operator to add or subtract a given number from the HEX code to arrive at the border color. In this instance the border color is #B02222
, which gives the button a slightly darker color than that of the main button.
The beauty of using variables here is that if you suddenly decide you want to change the color scheme on your site, you only need to change it in one place; all of the borders will be updated at the same time to a suitable shade that fits in with the new color. We can take this a step further and mix in some gradients in the LESS file. This works best if you choose a mid-point color and use this to define your gradient. A good example is to make the start of the gradient lighter and finish on a slightly darker color:
body { padding: 20px; } @color-button: #faa51a; input.submit { @color: #faa51a; background: -webkit-gradient(linear, left top, left bottom, from(@color + #151515), to(@color - #151515)); background: -moz-linear-gradient(top, @color + #151515, @color - #151515); border:1px solid @color-button - #222; padding:5px 12px; }
This results in a button with a nice looking transition effect as shown in the following screenshot: