在不改变输入大小的情况下为占位符填充

时间:2015-03-08 07:29:52

标签: css padding placeholder search-form

我做自适应搜索表单。搜索字段应占父div的100%宽度(父div的宽度将根据设备的分辨率而变化)。按钮"搜索"应始终在场地的右侧,不要向下移动。

A working version

但是有一个问题:文本"立即搜索" (占位符)太靠近田地边缘,我无法将其向右移动。在其他示例中,它移动字段填充的设置值。但是,如果我更改填充 - 字段本身向左移动,但我只需要移动文本!

#searchfield {
   padding: 10px 0 13px 0; /* Try to change the left padding here! All field shifts to the left! But I need only shift the placeholder text to right! */
}

3 个答案:

答案 0 :(得分:4)

尝试为id searchfield 添加text-align:center或添加 box-sizing:border-box; 声明。

尝试使用以下任何一个示例,它会按照您的预期将占位符移动到右侧,这些也将支持更低版本。

Example1(使用box-sizing:border-box声明)

#searchfield {
     padding: 10px 0 13px 0px;
     box-sizing: border-box;
}

Example2(使用text-align:center声明)

#searchfield {
      text-align:center;
}

答案 1 :(得分:1)

您仍然可以使用padding移动占位符文字,其风格为box-sizing: border-box;声明。

box-sizing: border-box;让用户代理包含padding / border到该框的width / height

#searchfield {
  width: 100%;
  border: 1px solid #ccc;
  padding: 10px 0 13px 10px;
  box-sizing: border-box;
  /* other declarations... */
}

由于简洁,省略了供应商前缀。



#sidebar {
  width: 20%;
  background: #ccc;
  height: 300px;
  padding: 20px;
}
#search {
  width: 100%;
  height: 50px;
  position: relative;}
#searchfield {
  width: 100%;
  border: 1px solid #ccc;
  margin: 0;
  padding: 12px 0 13px 10px;
  box-sizing: border-box;
  position: absolute;
  right: 0;
}
#searchsubmit {
  width: 60px;
  height: 41px;
  background: red 0 0;
  border: 0;
  overflow: hidden;
  cursor: pointer;
  right: 0;
  position: absolute;
}

<html>
 <body>
  <div id="sidebar">
    <div id="search">
      <form id="searchform" method="get" action="/index.php" _lpchecked="1">
      <input type="text" name="s" id="searchfield" placeholder="Search now">
      <input type="submit" id="searchsubmit" value="Search">
      </form>
     </div>
   </div>
 </body>
</html>
&#13;
&#13;
&#13;

值得一提的是border-box is supported in IE8+以及现代网络浏览器。

答案 2 :(得分:0)

无需使用绝对位置。试试这段代码:

<html>
 <body>
  <div id="sidebar">
    <div id="search">
      <form id="searchform" method="get" action="/index.php" _lpchecked="1">
      <input type="text" name="s" id="searchfield" placeholder="Search now">
      <input type="submit" id="searchsubmit" value="Search">
      </form>
     </div>
   </div>
 </body>
</html>


#sidebar {
  width: 20%;
  background: #ccc;
  height: 300px;
  padding: 20px;
}
#search {
  width: 100%;
  height: 50px;
  position: relative;}
#searchfield {
  width: calc(100% - 60px);
  border: 1px solid #ccc;
  margin: 0;
  padding: 10px 0 13px 20px; /* Try to change the left padding here! All field shifts to the left! But I need only shift the placeholder text to right! 
  position: absolute;*/
  right: 0;
  float:left;
  box-sizing:border-box;
}
#searchsubmit {
  width: 60px;
  height: 41px;
  background: red 0 0;
  border: 0;
  overflow: hidden;
  cursor: pointer;
  right: 0; 
  float:left;
  box-sizing:border-box;
}

code pen

上的现场演示
相关问题