如何设置文本输入的样式,以便左侧有一个图标而不使用背景图像?

时间:2016-05-25 02:37:37

标签: html css

我尝试创建类似于Pearson的TestNav登录中显示的用户名和密码输入的文本输入(忽略黄色框)。

Pearson's TestNav Login

要在左侧制作图标,他们会使用background-image属性。我想知道是否有可能在不使用任何图像的情况下实现相同的效果。 I've gotten pretty close,但有两个问题。图标框右侧的边框是四舍五入的,如果单击图标,则它不会聚焦输入。我尝试使输入框背景透明并将图标放在其后面,但如果网站位于密码管理器中,则Chrome会覆盖背景颜色。

这是我尝试的CSS / HTML: HTML:

<div class="field">
  <input type="text">
  <div class="icon">
    <i class="fa fa-user"></i>
  </div>
</div>

CSS:

.field input {
    outline: none;
    border: 0px solid #fff;
    font-size: 14px;
    padding: 5px 5px 5px 44px;
    position: absolute;

    width: 260px;
    height: 40px;

    box-sizing: border-box;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0px 0px 0px 0px rgba(186,213,232,1);

    transition: border 0.5s ease-in-out 0s, box-shadow 0.3s ease-in-out 0s;
}

.field input:focus {
    border: 1px solid #2977FF;
    box-shadow: 0px 0px 10px 2px rgba(186,213,232,1);
}

.field .icon {
  display: flex;
    justify-content: center;
    align-items: center;


    height: 36px;
    width: 36px;
    padding: 0;
    border: 1px solid #eee;
    border-radius: 3px;
    margin: 1px 0px 0px 1px;
    position: absolute;
    background-color: #eee;
}

3 个答案:

答案 0 :(得分:2)

尝试将图标div更改为标签

<div class="field">
  <input type="text" id="this-input">
  <label class="icon" for="this-input">
    <i class="fa fa-user"></i>
  </label>
</div>

当点击它时,它会聚焦它引用的元素(对于=&#34; this-input&#34;)

修复边框半径。从

更改图标样式
border-radius: 3px;

border-radius: 3px 0 0 3px;

从左上角开始,左上角为3px,右上角为0,右下角为0,左下角为3px

答案 1 :(得分:0)

你可以使用:输入:之前和样式,用像fontawesome这样的图标字体作为内容。

示例:

<input type="text" id="this-input" class="icon-whatever" />

答案 2 :(得分:0)

可以通过使用border-radius来删除圆形,就像你的情况一样,     
边框右上角半径:0像素;
    边界右下半径:0像素;

您需要Javascript来关注输入标记。因为.icon类不是输入标记的一部分(输入标记是单独的,而.icon在您的代码中是单独的)。为了做到这一点,使用focus()函数

我希望这会有所帮助

function cool()
{
		document.getElementById("cool").focus();
}
.field input {
    outline: none;
    border: 0px solid #fff;
    font-size: 14px;
    padding: 5px 5px 5px 44px;
    position: absolute;

    width: 260px;
    height: 40px;

    box-sizing: border-box;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0px 0px 0px 0px rgba(186,213,232,1);

    transition: border 0.5s ease-in-out 0s, box-shadow 0.3s ease-in-out 0s;
}

.field input:focus {
    border: 1px solid #2977FF;
    box-shadow: 0px 0px 10px 2px rgba(186,213,232,1);
}

.field .icon {
  display: flex;
    justify-content: center;
    align-items: center;
    height: 36px;
    width: 36px;
    padding: 0;
    border: 1px solid #eee;
    border-radius: 3px;
	border-top-right-radius:0px;
	border-bottom-right-radius:0px;
    margin: 1px 0px 0px 1px;
    position: absolute;
    background-color: #eee;
}
<div class="field">
  <input type="text" id=cool>
  <div class="icon" onclick="cool()">
    <i class="fa fa-user"></i>
  </div>
</div>