2015-10-19 92 views
2

我有一個<input>元素,我無法修改其周圍的HTML,但我想在其中添加一個glyphicon(<i class="glyphicons glyphicons-some-icon"/>)。我希望能用CSS做到這一點,但我似乎無法使用:after。我認爲像下面這樣會產生該元素:如何使用CSS:將Glyphicon元素添加到輸入之後

#my-input { 
    content: attr(class, 'glyphicons glyphicon-some-icon'); 
    content: '<i/>'; 
} 

但它沒有。誰能理解:after更好地解釋我如何使用:after生成想要的<i class="glyphicons glyphicons-some-icon"/>

+4

你不能。 ':之前'和':之後'僞元素插入元素內。 ''元素不能生孩子,因此不幸的是不能生孩子。 – misterManSam

+0

你可以通過查看Bootstrap的樣式表來找到這些: http://stackoverflow.com/questions/19740700/glyphicons-bootstrap-icon-font-hex-value –

+0

這不可能與純粹的CSS http://stackoverflow.com/ question/2587669/can-i-use-the-after-pseudo-element-on-an-input-field – NooBskie

回答

8

之前:後一個容器中,這意味着可以 使用它與一個結束標記元素中施加see explanation

看下面的例子。實現你想要的。

備註:父母的位置是相對的,所以冰冷的絕對位置將取決於父母的頂部和底部。

.myInput:after { 
 
    font-family: FontAwesome; 
 
    content: "\f0a9"; 
 
    position: absolute; 
 
    top: 3px; 
 
    left: 7px; 
 
} 
 
.my{ 
 
position:relative 
 
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" /> 
 

 
<div class="my"> 
 

 
    <div class="myInput"> 
 
    <input type="text" /> 
 
    </div> 
 

 
</div>

OR

.mystyle:before { 
 
    font-family: FontAwesome; 
 
    content: "\f0a9"; 
 
} 
 
.myInput { 
 
    position: relative; 
 
} 
 
.myInput div { 
 
    position: absolute; 
 
    top: 3px; 
 
    left: 5px; 
 
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet" /> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="myInput"> 
 
    <input class="mystyle" type="text" value="" /> 
 
    <div class="mystyle"></div> 
 
</div>

+0

這是一個很好的方法!較少的標記更清晰 – Vladyn

1

這可能會達到什麼樣的你正在嘗試做的。

[data-icon]:before { 
 
    font-family: icons; 
 
    content: attr(data-icon); 
 
    speak: none; /* Not to be trusted, but hey. */ 
 
    position: absolute; 
 
}
<h2 id="stats" aria-hidden="true" data-icon="&#x21dd;"> 
 
<input type="text"/> 
 
</h2>

OR

.glyphicon-search:before { 
 
    position: absolute; 
 
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
 

 
<div class="glyphicon glyphicon-search"> 
 
<input type="text"/> 
 
</div>

相關問題