使用 HTML+CSS 在输入上显示跨度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20653207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display span over input with HTML+CSS
提问by EasyDevop
I want to display a span element over an input element with CSS. How can I do this. My current code:
我想在带有 CSS 的输入元素上显示 span 元素。我怎样才能做到这一点。我目前的代码:
<input type="url" placeholder="e.g. www.google.com" />
<span>http://</span>
How can I display the span element on the input element so that the users know there is no need to enter http:// so it would look like if there's already a value in but then it is the span element on the input? I assume I can do that with CSS positioning.
如何在输入元素上显示 span 元素,以便用户知道不需要输入 http:// ,所以看起来好像已经有一个值,但它是输入上的 span 元素?我想我可以通过 CSS 定位来做到这一点。
I cannot use placeholder as I don't want it to be removed.
我不能使用占位符,因为我不希望它被删除。
回答by Morpheus
As you have mentioned you need to use positioning and wrap your input with span into div or some other element.
正如您所提到的,您需要使用定位并将带有 span 的输入包装到 div 或其他一些元素中。
.wrapper {
position: relative;
}
input {
padding-left: 48px;
}
.wrapper span {
position: absolute;
left: 2px;
}
<div class="wrapper">
<input type="url" placeholder="e.g. www.google.com" />
<span>http://</span>
</div>
回答by Benjamin Schulz
This is a bit of an old post, but there is a more simple way of doing this and without using positioning. Wrap each element of the form in a list item and set the display to 'inline-block' and the display of the span to 'block' like this -
这是一篇旧帖子,但有一种更简单的方法可以做到这一点,而且不使用定位。将表单的每个元素包装在一个列表项中,并将显示设置为“inline-block”,将跨度的显示设置为“block”,如下所示 -
li{
display: inline-block;
}
li span{
display: block;
}
You would then need to swap the order of the html elements like so -
然后,您需要像这样交换 html 元素的顺序 -
<span>http://</span>
<input type="url" placeholder="e.g. www.google.com" />
You could however leave it the same if you wanted the span to display on the bottom of the input element.
但是,如果您希望跨度显示在输入元素的底部,则可以保持不变。
回答by caramba
something like this: fiddle
像这样:小提琴
* {
font-family: Arial, sans-serif;
font-size: 12px;
}
.row {
position:relative;
}
.row span {
position:absolute;
left:5px;
top:5px;
}
.row input {
padding-left: 40px;
line-height: 16px;
}
<div class="row">
<span>http://</span>
<input type="url" placeholder="e.g. www.google.com" />
</div>