In yesterday’s article we saw how images were handled in buttons within XForms. XForms will be, we hope, the evolution of forms HTML within XHTML v2. But, today, what we have to live with is HTML + CSS. That is why we will have to rely on the attributes of CSS to be able to create a button with a background image in CSS.
The general idea is to use the attribute background-image
, which puts a background image on the page element on which it is applied. To do this, we are going to create a class that we will call «imagebutton», which we can apply to any button on our page.
The first thing is to define said class, we have to do this with the attribute style
. This element has a type attribute. This attribute is used to indicate which style will be defined within the label. In our case it will be text/css.
The code will be the following:
.imagebutton{ background-image:url(image.jpg); }
In this code you must indicate that the value of the attribute background-image
is not directly the name of the image, but we must use a URL. That is why the name of the image comes after the url function. Its value could be any URL address where the image was.
The next thing we will have to do is assign the class to a button. At this point say that the language HTML provides us with two ways to get a button.
Through the input class and the type equal to button
<input type="button" value="Button text">
Through the button element
<button value="Button text"></button>
To apply the class we must use the attribute style
. In the case of choosing the first way to paint a button, the line of code would remain:
<input type="button" class="imagebutton" value="Button text">
At this point we encounter a series of problems. For example:
- The button adapts to the size of the text, so if the image is larger than the text, the image will not be seen in its entirety.
- The image is repeated as many times as needed to fill the button space. This can be a problem if we are using a small image
To alleviate these effects and so that we have at least one curious button left. We can play with a set of attributes, which are:
height
, to define the height of the button.
width
, to define the width of the button
background-repeat
, to identify the number of times the image will be repeated
background-position
, image position: top, bottom, center.
Finally, the class code would look like this:
.imagebutton{ background-image:url(image.jpg); background-repeat:no-repeat; height:100px; width:100px; background-position:center; }
In this way we will have already managed to create a button with a background image in CSS. I hope it has been useful to you.