焦点边框导致背景图像跳变

时间:2018-07-28 16:44:15

标签: html css

当输入具有焦点时,是否仍然可以阻止背景图像跳动。

获得焦点时,会在输入中添加2px边框,但这会导致图像跳转。

添加background-attachment: fixed会使图像消失。

.search_box {
  border: 1px solid #0065bd;
  background-color: #fff;
  background: url("http://png-5.findicons.com/files/icons/980/yuuminco/256/search.png");
  background-size: 20px 20px;
  background-repeat: no-repeat;
  background-position: left;
  padding-right: 20px !important;
  padding-top: 2px !important;
  padding-bottom: 2px !important;
  padding-left: 5px !important;
    height: 42px;
  width: 100%;
  padding: 6px 12px;
}

.search_box:focus {
  background-color: #d9effc;
  border: 2px solid #0065bd;
}
<input type="text" class="textbox search_box" name="keywords" />

3 个答案:

答案 0 :(得分:2)

首先,定义两个维度的背景位置。我强烈建议您以像素为单位。然后,在焦点样式上,将背景位置重置为-1px -1px以补偿新的额外边框像素。

.search_box {
  [...]
  background-position: 0 0;
}

.search_box:focus {
  [...]
  background-position: -1px -1px;
}

答案 1 :(得分:1)

使用box-shadow

我通常使用以下生成器生成我的:Box Shadow Generator

.search_box {
  border: 1px solid #0065bd;
  background-color: #fff;
  background: url("http://png-5.findicons.com/files/icons/980/yuuminco/256/search.png");
  background-size: 20px 20px;
  background-repeat: no-repeat;
  background-position: left;
  padding-right: 20px !important;
  padding-top: 2px !important;
  padding-bottom: 2px !important;
  padding-left: 5px !important;
    height: 42px;
  width: 100%;
  padding: 6px 12px;
}

.search_box:focus {
  background-color: #d9effc;
  box-shadow: 0px 0px 0px 2px rgba(0,101,189,1);
}
<input type="text" class="textbox search_box" name="keywords" />

答案 2 :(得分:1)

您可以在box-sizing: border-box;上使用.search_box使它的大小保持不变,即使边框更大,也可以使用margin-left: -1px;  在.search_box:focus上将其保留在同一位置。

.search_box {
  border: 1px solid #0065bd;
  background-color: #fff;
  background: url("http://png-5.findicons.com/files/icons/980/yuuminco/256/search.png");
  background-size: 20px 20px;
  background-repeat: no-repeat;
  background-position: left;
  padding-right: 20px !important;
  padding-top: 2px !important;
  padding-bottom: 2px !important;
  padding-left: 5px !important;
    height: 42px;
  width: 100%;
  padding: 6px 12px;
  box-sizing: border-box;
}

.search_box:focus {
  background-color: #d9effc;
  border: 2px solid #0065bd;
  margin-left: -1px;
}
<input type="text" class="textbox search_box" name="keywords" />

相关问题