March 16, 2011

repeating image background on input text field

Question by oipsl

I have a search bar that uses a background image that’s 200 by 25 px that uses the following css class

.searchBar{
    border-style: hidden;
    border-width: 0px;
    color: #FFFFFF;
    padding-left: 10px;
    padding-right: 10px;
    font-size:1em;
    background-image: url(images/searchBox2.gif);
    font-family: "calibri", "helvetica", sans-serif;
    margin-left:1%;
    width: 200px;
    height: 25px;
    outline: 0 none;
    vertical-align: middle;
    }

For some reason, it extends the element to a 220 by 27 field (the 10 padding on the left and right side and another 1 px from the top and bottom in another class) and the background image is repeated. It worked the way I wanted it before with the background not repeated until I recently added doctype html 4.01 transitional into my code. Here’s a link to a visual of what I mean:
Picture of Search Bar before and after

Answer by Starx

Padding adds up to total width of the element. See the example to know how to get same result.

Without padding

.searchbar {
    width: 200px;
}

With padding

.searchbar {
    width: 180px;
    padding: 0 10px; 
}

And to avoid the repeating background use background-repeat:no-repeat;

Here is your full solution

.searchBar{
    border-style: hidden;
    border-width: 0px;
    color: #FFFFFF;
    padding-left: 10px;
    padding-right: 10px;
    font-size:1em;
    background-image: url(images/searchBox2.gif);
    background-repeat: no-repeat;
    font-family: "calibri", "helvetica", sans-serif;
    margin-left:1%;
    width: 180px;
    height: 25px;
    outline: 0 none;
    vertical-align: middle;
    }

You can also use shorthand background to merge your background styles

background: url(images/searchBox2.gif) no-repeat;

You can also use shorthand padding to merge you padding-left and right

padding: 0 10px;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!