用CSS设计你的搜索框

  •   2009-07-31/13:29
  • 今天我将介绍一下如何使用CSS中的背景图片来设计你的搜索框。之前我使用别的方法来实现我的表单和搜索框,但是这种方法看起来会更容易些,所以我想将它与感兴趣的朋友分享。

    View Demo

    原始方式
    首先来让我们看看我的原始的使用<input type=”image” src=”image_url” />的方法:

    <form method="get" id="searchform" action="">
     <fieldset>
     <input type="text" value="" name="s" id="s" />
     <input type="image" src="img_url" id="searchsubmit" value="Search" class="btn" />
     </fieldset>
    </form>这看起来挺不错的,但是它有一个不好的地方,这个图片按钮不会和搜索框对其,我必须使用一个负的margin-top属性来修正这个bug。


    原始方法

    改良方法
    在这个改良版的方法中,我决定不再使用 type=”image” ,而是使用<button>标签,然后用CSS添加背景。这允许文本输入框和按钮自动对齐。我同样添加了a :focus伪类到最终效果(IE将不会支持这个,所以我添加了一个特殊的样式针对IE来隐藏这个效果)。 下面是这种方法的一些好处:

    很自然的对齐
    对按钮和输入框只使用了一张图片
    :focus 伪类支持它的浏览器
    添加hover 效果到按钮


    HTML

    <form method="get" id="searchform" action="">
    <fieldset class="search">
     <input type="text" class="box" />
     <button class="btn" title="Submit Search">Search</button>
    </fieldset>
    </form>CSS

    fieldset.search {
     border: none;
     width: 243px;
     margin: 0 auto;
     background: #222;
    }
    .search input, .search button {
     border: none;
     float: left;
    }
    .search input.box {
     color: #fff;
     font-size: 1.2em;
     width: 190px;
     height: 30px;
     padding: 8px 5px 0;
     background: #616161 url(search_bg.gif) no-repeat;
     margin-right: 5px;
    }
    .search input.box:focus {
     background: #616161 url(search_bg.gif) no-repeat left -38px;
     outline: none;
    }
    .search button.btn {
     width: 38px;
     height: 38px;
     cursor: pointer;
     text-indent: -9999px;
     background: #fbc900 url(search_bg.gif) no-repeat top right;
    }
    .search button.btn:hover {
     background: #fbc900 url(search_bg.gif) no-repeat bottom right;
    }IE特别注释

    <!--[if lte IE 7]>
    <link rel="stylesheet" type="text/css" href="ie.css" />
    <![endif]-->IE 样式- ie.css
    朋友评论说如果输入文字过多IE6和IE7会水平滚动背景图片,所以我的方法是专门为IE使用一个单独的背景图片 ,而且不是让它左对齐,我翻转了它,通过让背景图片右对齐来修正这个。

    .search input.box {
     background: url(search_bg_ie.gif) no-repeat right bottom;
      /* 专门为IE的独立背景图片,而且这个图篇必须是右对齐的。***/
    }


    评论 {{userinfo.comments}}

    {{money}}

    {{question.question}}

    A {{question.A}}
    B {{question.B}}
    C {{question.C}}
    D {{question.D}}
    提交

    驱动号 更多