Display span over input with HTML+CSS
Asked Answered
L

3

7

I want to display a span element over an input element with CSS. How can I do this. My current code:

<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.

I cannot use placeholder as I don't want it to be removed.

Lentamente answered 18/12, 2013 at 8:38 Comment(0)
P
20

As you have mentioned you need to use positioning and wrap your input with span into div or some other element.

.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>

Example

Picaresque answered 18/12, 2013 at 8:43 Comment(0)
R
2

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 -

li{
   display: inline-block;
}

li span{
   display: block;
}

You would then need to swap the order of the html elements like so -

<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.

Resale answered 22/12, 2015 at 14:40 Comment(0)
K
1

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>
Kuhl answered 18/12, 2013 at 8:41 Comment(3)
Your fiddle doesn't show the span OVER the input, but to its side.Fyn
updated the answer (changed margin-left to padding-left)Kuhl
This works, but you can tell that the text from the input is on top of the span or vice versa. It doesn't look flawless. How can you overlay a span on an input, and have each letter cover the span beneath it without that odd, letter over letter, look?Garbers

© 2022 - 2024 — McMap. All rights reserved.