Adding A Space To A Phone Number With Just Css
I have a page which generates a phone number in HTML, like this:
01987123456
What I want is to simply put a space inside the number, like so:Solution 1:
I was interested to see if this could be done with CSS, even if it shouldn't be done! The following is quite hacky, ideally the phone number would be formatted server side or, if that isn't an option, with JavaScript.
A few caveats:
- This requires an attribute to be added to
.phone
for the pseudo element to use. This may or may not be a deal breaker given that you seem to have limited access to the HTML - If the phone number is not in a suitable format (e.g. something like 01 987123456) it will not display correctly
- A nasty little hack is used for IE as it doesn't calculate the
width
of the pseudo element correctly usingch
for some reason. Credit to SW4 for this: https://stackoverflow.com/a/20541859 - A solid background colour is required
The general idea behind this is as follows:
.phone
text-indent: 1ch;
on.phone
moves the whole text to the left by one character.phone
is set toposition: relative;
to allow the pseudo element to be positioned relatively to itwhite-space: nowrap;
ensures that this doesn't wrap onto a new line if there is a break in the number
.phone:before
background-color: white;
masks the digits in.phone
border-right: 1ch solid white;
hides the sixth digit in.phone
, in effect this is the spacecontent: attr(data-phone);
uses thedata-phone
attribute on.phone
to populate the pseudo element with the same number
left: 0;
,position: absolute;
andtop: 0;
are used to position the pseudo elementoverflow: hidden;
hides any characters over the 5 character limittext-indent: 0;
resetstext-indent: 1ch;
set on.phone
width: 5ch;
ensures that the pseudo element is only 5 characters long- The weird media query is the hack to target IE
Tested and working in FF 38.0.5, Chrome 43.0.2357.124 m and IE 11. Browsers not supporting the ch
unit (such as Opera 12.17 and Windows Safari 5.1.7) seem to show the phone number in its natural state.
.phone {
position: relative;
text-indent: 1ch;
white-space: nowrap;
}
.phone:before {
background-color: white;
border-right: 1ch solid white;
content: attr(data-phone);
display: block;
left: 0;
overflow: hidden;
position: absolute;
text-indent: 0;
top: 0;
width: 5ch;
}
@media screen and (min-width:0\0) and (min-resolution: +72dpi) {
.phone:before {
width: 5.8ch;
}
}
<divclass="phone"data-phone="01987123456">01987123456</div>
JS Fiddle:https://jsfiddle.net/scarjnb1/
Solution 2:
It's not possible using CSS, just JavaScript. Then it'd be:
<divid="phone">01987123456</div><script>var el = document.getElementById('phone');
phone.innerText = phone.innerText.replace(/^(\d{5})/, '($1) ');
</script>
Post a Comment for "Adding A Space To A Phone Number With Just Css"