CSS text-transform capitalize on all caps

2019-01-03 14:53发布

Here is my HTML:

<a href="#" class="link">small caps</a> & 
<a href="#" class="link">ALL CAPS</a>

Here is my CSS:

.link {text-transform: capitalize;}

The output is:

Small Caps & ALL CAPS

and I want the output to be:

Small Caps & All Caps

Any ideas?

标签: css
15条回答
在下西门庆
2楼-- · 2019-01-03 15:27

I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.

Regex solutions are the fastest for sure.

Here is the jsPerf: https://jsperf.com/capitalize-jwaz

There are 2 regex solutions.

The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.

If you only want to capitalize letters that are preceded by a space then use the second regex

/(^[a-z]|\s[a-z])/g
查看更多
甜甜的少女心
3楼-- · 2019-01-03 15:28

JavaScript:

var links = document.getElementsByClassName("link");
for (var i = 0; i < links.length; i++) {
  links[i].innerHTML = links[i].innerHTML.toLowerCase();
}

CSS:

.link { text-transform: capitalize; }

What Khan "ended up doing" (which is cleaner and worked for me) is down in the comments of the post marked as the answer.

查看更多
闹够了就滚
4楼-- · 2019-01-03 15:33

link {text-transform:lowercase !important;}

link:first-letter {text-transform:uppercase;}

capitalize transforms every first letter of a word to uppercase, but it does not transform the other letters to lowercase. So, Use text-transform: uppercase on the first letter, and text-transform: lowercase on the rest. Worked for me.

查看更多
小情绪 Triste *
5楼-- · 2019-01-03 15:34

if you are using jQuery; this is one a way to do it:

$('.link').each(function() {
    $(this).css('text-transform','capitalize').text($(this).text().toLowerCase());
});

Here is an easier to read version doing the same thing:

//Iterate all the elements in jQuery object
$('.link').each(function() {

    //get text from element and make it lower-case
    var string = $(this).text().toLowerCase();

    //set element text to the new string that is lower-case
    $(this).text(string);

    //set the css to capitalize
    $(this).css('text-transform','capitalize');
});

Demo

查看更多
萌系小妹纸
6楼-- · 2019-01-03 15:34

all wrong it does exist --> font-variant: small-caps;

text-transform:capitalize; just the first letter cap

查看更多
再贱就再见
7楼-- · 2019-01-03 15:35

May be useful for java and jstl.

  1. Initialize variable with localized message.
  2. After that it is possible to use it in jstl toLowerCase function.
  3. Transform with CSS.

In JSP

1.

<fmt:message key="some.key" var="item"/>

2.

<div class="content">
  <a href="#">${fn:toLowerCase(item)}</a>
</div>

In CSS

3.

.content {
  text-transform:capitalize;
}
查看更多
登录 后发表回答