如何使用CSS将大写文本转换为标题大小写

如何使用CSS将大写文本转换为标题大小写

问题描述:

如果您正在阅读本文,您可能会注意到CSS属性text-transform:capitalize;不会将THIS转换为This.而是将非首字母保留为大写,因此在这种情况下,转换无效.那么我们怎样才能达到这个结果呢?

If you're reading this you probably noticed that the CSS property text-transform:capitalize; does not convert THIS into This. Instead the, non-initial characters remain capitalized, so the transformation has no effect in this case. So how can we achieve this result?

我经常看到这个问题,大多数答案都可以通过javascript来快速完成.这将起作用,但是如果您正在为Wordpress,Drupal或Joomla等PHP CMS编写或自定义模板/主题,则没有必要.

I've seen this asked often and most answers are quick to promote using javascript to accomplish this. This will work, but it is unnecessary if you are writing or customizing a template/theme for a PHP CMS like Wordpress, Drupal, or Joomla.

坏消息是,没有text-transform : title-case这样的东西可以保证结果以标题区分大小写.好消息是,有一种方法可以做到这一点,它不需要javascript(在这种情况下通常会建议这样做).如果要为CMS编写主题,则可以使用strtolower()和 ucwords() 将相关文本转换为标题大小写.

The bad news is that there is no such thing as text-transform : title-case which would guarantee the result to be title cased. The good news is that there IS a way to do it, which doesn't require javascript (as is often suggested for this situation). If you are writing a theme for a CMS you can use strtolower() and ucwords() to convert the relevant text to title case.

之前(此方法无效):

<style>
.title-case{ text-transform:capitalize; }
</style>
<span class="title-case">ORIGINAL TEXT</span>

之后:

<?php echo ucwords( strtolower('ORIGINAL TEXT') ); ?>

如果要编写主题,则可能使用变量而不是文本字符串,但是函数和概念的工作方式相同.这是使用本机Wordpress函数 get_the_title()的示例,以将页面标题作为变量返回:

If you are writing a theme, you'll probably be working with variables instead of text strings, but the function and the concept work the same way. Here's an example using the native Wordpress function get_the_title() to return the page title as a variable:

<?php
$title = get_the_title();
$title = strtolower($title);
$title = ucwords($title); 
<h1>
<?php echo $title;
</h1> 
?>

希望这对某人有帮助.编码愉快.

Hope this helps someone. Happy coding.