Fashion Initial Character Of Each Word In Passage

I'm attempting to style the first letter of each word in a paragraph using CSS and was looking to incorporate some animation with greensock. However, the actual requirement is to style the first letter of each word, not just the first letter of the paragraph.

Any suggestions or ideas on how to achieve this?

p{
  font-size:150%;
  color:#000000;
}
p::first-letter {
  font-size: 200%;
  color: #ff0000;
}
<p>Hello This Is The Title</p>

UPDATE I attempted the following approach (adding span tags and targeting the first element of each span), but it did not work:

p span:nth-child(1)::first-letter {
   font-size: 200%;
   color: #ff0000;
}

Answer №1

utilize the split(" ") method to create an array from a string, and use forEach() to iterate through each word. Next, utilize slice(0,1) to remove the first letter of each word and then append it with span. Finally, apply CSS effects to the span element.

var str = $('p').text().split(" ");
$('p').empty();
str.forEach(function(a) {
  $('p').append('&nbsp;<span>' + a.slice(0, 1) + '</span>' + a.slice(1))
})
p {
  font-size: 150%;
  color: #000000;
}

span {
  font-size: 200%;
  color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello This Is The Title</p>

Answer №2

const element = document.getElementById('text')

const styleText = (text) => '<span class="styled">' + text + '</span>'

const newText = element.innerText.split(' ').map(word => word.split('').map((letter, index) => (index === 0) ? styleText(letter) : letter).join('')).join(' ')

element.innerHTML = newText
.styled {
  color: blue;
}
<p id="text">Hello World</p>

Answer №3

Forget about the css first-word selector. You can easily achieve this using jquery.

Approach 1: Customize only the first word of a paragraph.

$(function() {
    $('p').each(function() {
        var text = this.innerHTML;
        var firstSpaceIndex = text.indexOf(" ");
        if (firstSpaceIndex > 0) {
            var substrBefore = text.substring(0,firstSpaceIndex);
            var substrAfter = text.substring(firstSpaceIndex, text.length)
            var newText = '<span class="firstWord">' + substrBefore + '</span>' + substrAfter;
            this.innerHTML = newText;
        } else {
            this.innerHTML = '<span class="firstWord">' + text + '</span>';
        }
    });
});
.firstWord{ color:red; font-size:20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Applying styles to the first word of a paragraph.</p>

Approach 2 : Applying styles to each first letter of a paragraph line

$(document).ready(function() {
    var words = $('p').text().split(' ');
    var html = '';
    $.each(words, function() {
        html += '<span class="firstLetter">'+this.substring(0,1)+'</span>'+this.substring(1) + ' ';
    });
    $('p').html(html);
});
.firstLetter{ color:red; font-size:20px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Styling the first letter of each word in a paragraph.</p>

Answer №4

Unfortunately, the pseudo-element you're seeking, :first-letter-every-word, does not currently exist in CSS. While :first-letter and :first-line are available options, they do not cater to your specific requirement.

To work around this limitation, one approach could involve enveloping the initial letter of each word within a <span> element. Alternatively, consider exploring JavaScript-based solutions as another potential workaround.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ajax continues to repeatedly redirect to the PHP page

I currently have a Shopify store and I am looking to incorporate a form on the product page. However, I am facing an issue where when I try to submit the form using AJAX with an external link, it redirects to the external page instead of staying on the cur ...

Mapping data visually

Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...

Initiate a basic GET command

I am looking for a way to send a basic GET request to my server, but I have run into an issue with the x-requested-with header that is sent by .ajax. Unfortunately, my server does not understand this header. $.ajax({ ...

Issue with loading partial view in CodeIgniter using AJAX

My ajax function is working when trying to load a specific view (createClass.php), but it isn't functioning for other views like classAction.php. script: //--------------this works--------------- $(function(){ $(".classloader").click(function( ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

Adjust the size of the FabricJS canvas within a child component in VueJS

In my project, I am using VueJS and FabricJS to create a dynamic canvas that changes size based on user input. The goal is to have the canvas adjust its dimensions as soon as the user enters new values in the sidebar component. Despite using $emit from ch ...

Generating a three-dimensional sphere from flat coordinates with the help of sine and cosine functions

I am trying to achieve mapping a set of 2D coordinates to a 3D surface of a sphere. To accomplish this, I am starting with an array of xy coordinates. Using the following loops, I am generating 20*20 xy coordinates ranging from 0 to 1 on each axis: var p ...

Tips for incorporating seamless animation effects to an element with jQuery

As I work on coding the navbar for my HTML website, I'm incorporating Bootstrap for styling and using a jQuery function to change the color of the navbar dynamically. However, I want to ensure that the color transitions smoothly when it changes. How c ...

Tips for shutting down an open section within a jQuery Accordion?

I am having trouble closing the active panel using jQuery. The rest of my code is functioning perfectly, but for some reason, I can't get the active panel to close. Currently, the code is working correctly in that only one panel can be open at a time ...

Issue with event delegation when using if-else conditions is not being resolved

I have set up an event listener on an HTML container, and when the user clicks on the play again button, the code inside the 'if' statement should be executed. However, nothing happens when clicking on the play again button and no logs are output ...

Tips for ensuring an image fits perfectly within a MUI grid

I am currently working on an application that involves a collection of cards. My tech stack includes React and MUI v5. One issue I've been facing is with the grid layout, specifically in trying to keep the image size consistent within the grid item. ...

Retrieving data from an API using various parameters

Looking to pass multiple parameters into a URL and fetch data for each parameter in a single call? For example, if param_1 and param_2 have different data, you can use axios to make one call to get both sets of data. const data_1 = "param_1"; c ...

Display the column every time the user types something into the search bar

Currently working on an Angular project and I'm trying to figure out how to make the middle column visible whenever the user enters text in the search bar. At the moment, I have a search bar for user input and three flex columns. The middle column is ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

executing a javascript function in PHP following form submission

Having trouble calling a javascript function after submitting a form and experiencing errors? New to PHP and seeking assistance. Any advice is appreciated. if(!empty($varAccountType)) { <?php if($varAccountType=='Free Account') { ...

Utilizing jQuery to seize events and handle AJAX callbacks

I am attempting to accomplish a simple task: capture any click event and send the URL to a PHP script. When using alert(a); the ajax.php is called every time. However, if I remove it, only once in every 20 clicks will work. I am wondering if this is due t ...

Create a search feature based on names utilizing Node Express in conjunction with SQL database

After deciding to create an API with a search feature using SQL queries in node express, this is how I structured my code: app.get('/search/:query', (req, res) => { pool.getConnection((err, connection) => { if(err) throw err ...

Incorporating the angular UI router effectively by reusing the same templateUrl and controller multiple times

Exploring the AngularUI Router framework for the first time, I am curious about how to enhance the code snippet below. Everything is functioning well at the moment, but as the project progresses, it will feature 20 questions or more. I want to avoid repea ...

Continuous Advancement Meter

I have implemented a progress bar, but I am encountering some issues with it. The progress bar is supposed to complete in 5 seconds. However, the value updates every second rather than continuously, causing it to pause intermittently. DEMO HTML <dx-p ...

creating a JSON array within a function

I am currently developing an Angular application and working on a component with the following method: createPath(node, currentPath = []){ if(node.parent !==null) { return createPath(node.parent, [node.data.name, ...currentPath]) } else { retu ...