First word in css

This one has me kind of stumped. I want to make the first word of all the paragraphs in my #content div at 14pt instead of the default for the paragraphs (12pt). Is there a way to do this in straight CSS or am I left wrapping the first word in a span to accomplish this?

Paulie_D's user avatar

Paulie_D

107k13 gold badges135 silver badges158 bronze badges

asked Sep 11, 2008 at 1:13

dragonmantank's user avatar

dragonmantankdragonmantank

15.2k20 gold badges83 silver badges92 bronze badges

1

I have to disagree with Dale… The strong element is actually the wrong element to use, implying something about the meaning, use, or emphasis of the content while you are simply intending to provide style to the element.

Ideally you would be able to accomplish this with a pseudo-class and your stylesheet, but as that is not possible you should make your markup semantically correct and use <span class="first-word">.

answered Sep 11, 2008 at 16:34

Prestaul's user avatar

6

Same thing, with jQuery:

$('#links a').each(function(){
    var me = $(this);
    me.html( me.text().replace(/(^w+)/,'<strong>$1</strong>') );
  });

or

$('#links a').each(function(){
    var me = $(this)
       , t = me.text().split(' ');
    me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );
  });

(Via ‘Wizzud’ on the jQuery Mailing List)

answered Jun 29, 2010 at 9:43

Jon Hadley's user avatar

Jon HadleyJon Hadley

5,1768 gold badges40 silver badges65 bronze badges

1

Sadly even with the likes of CSS 3 we still do not have the likes of :first-word :last-word etc using pure CSS. Thankfully there’s almost a JavaScript nowadays for everything which brings me to my recommendation. Using nthEverything and jQuery you can expand from the traditional Pseudo elements.

Currently the valid Pseudos are:

  • :first-child
  • :first-of-type
  • :only-child
  • :last-child
  • :last-of-type
  • :only-of-type
  • :nth-child
  • :nth-of-type
  • :nth-last-child
  • :nth-last-of-type

And using nth Everything we can expand this to:

  • ::first-letter
  • ::first-line
  • ::first-word
  • ::last-letter
  • ::last-line
  • ::last-word
  • ::nth-letter
  • ::nth-line
  • ::nth-word
  • ::nth-last-letter
  • ::nth-last-line
  • ::nth-last-word

answered Mar 24, 2015 at 20:36

Simon Hayter's user avatar

Simon HayterSimon Hayter

3,11027 silver badges52 bronze badges

You have to wrap the word in a span to accomplish this.

answered Sep 11, 2008 at 1:17

hazzen's user avatar

hazzenhazzen

17k6 gold badges41 silver badges33 bronze badges

Pure CSS solution:

Use the :first-line pseudo-class.

display:block;
Width:40-100px; /* just enough for one word, depends on font size */
Overflow:visible; /* so longer words don't get clipped.*/
float:left; /* so it will flow with the paragraph. */
position:relative; /* for typeset adjustments. */

Didn’t test that. Pretty sure it will work fine for you tho.
I’ve applied block rules to pseudo-classes before.
You might be stuck with a fixed width for every first word,
so text-align:center; and give it a nice background or
something to deal with the negative space.

Hope that works for you. :)

-Motekye

Carlos Vásquez Polanco's user avatar

answered Nov 23, 2011 at 14:17

Motekye Guakein's user avatar

4

Use the strong element, that is it’s purpose:

<div id="content">
    <p><strong>First Word</strong> rest of paragraph.</p>
</div>

Then create a style for it in your style sheet.

#content p strong
{
    font-size: 14pt;
}

answered Sep 11, 2008 at 1:21

Dale Ragan's user avatar

Dale RaganDale Ragan

18.2k3 gold badges53 silver badges70 bronze badges

6

Here’s a bit of JavaScript and jQuery I threw together to wrap the first word of each paragraph with a <span> tag.

$(function() {
    $('#content 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>';
        }
    });
});

You can then use CSS to create a style for .firstWord.

It’s not perfect, as it doesn’t account for every type of whitespace; however, I’m sure it could accomplish what you’re after with a few tweaks.

Keep in mind that this code will only execute after page load, so it may take a split second to see the effect.

answered Feb 19, 2013 at 22:35

user1171848's user avatar

user1171848user1171848

2763 silver badges10 bronze badges

There isn’t a plain CSS method for this. You might have to go with JavaScript + Regex to pop in a span.

Ideally, there would be a pseudo-element for first-word, but you’re out of luck as that doesn’t appear to work. We do have :first-letter and :first-line.

You might be able to use a combination of :after or :before to get at it without using a span.

answered Sep 11, 2008 at 1:21

Rob Allen's user avatar

Rob AllenRob Allen

17.3k5 gold badges51 silver badges70 bronze badges

An easy way to do with HTML+CSS:

TEXT A <b>text b</b>

<h1>text b</h1>

<style>
    h1 { /* the css style */}
    h1:before {content:"text A (p.e.first word) with different style";    
    display:"inline";/* the different css style */}
</style>

Joundill's user avatar

Joundill

6,55412 gold badges36 silver badges50 bronze badges

answered Nov 14, 2020 at 18:42

Noelia García's user avatar

I find JavaScript being the best way to achieve this.
Below is the JS code to set an element’s First Word as the element’s innerText

let text = document.querySelector('.menu_text');
const words = menu_text.innerHTML.toString().split(' ');
text.innerText = words[0];

answered Mar 13, 2022 at 12:32

Schäfer's user avatar

SchäferSchäfer

1811 gold badge1 silver badge7 bronze badges

My idea to make it possible is use a php function to get a first word of the string and then use a CSS styling to give this word different color. Here how i use this for H1 tag. Here how you can get first word if you work on PHP.

<?php  
    $string = "Read more";
    echo '<h1><span>' . strtok($string, " ") . '</span>' . $string . '</h1>'; 
?>

CSS

h1 {
    position: relative;
    display: inline-block;
    margin: 0;
}
h1 > span {
    position: absolute;
    color: blue;
    text-shadow: 0px 0px 1px blue;
}

Here is the snippet only for demonstration how it looks when your PHP script will return the HTML code on your page or you want use only a HTML.

h1 {
    position: relative;
    display: inline-block;
    margin: 0;
}
h1 > span {
    position: absolute;
    color: blue;
    text-shadow: 0px 0px 1px blue;
}
<h1><span>Read</span>Read more</h1>

answered Dec 16, 2022 at 2:00

X9DESIGN's user avatar

X9DESIGNX9DESIGN

7741 gold badge10 silver badges23 bronze badges

Insert Span Tag in your paragraph text. For Example-
<p><span>Hello</span>My Name Is Dot</p
and then style the first letter.

answered Nov 1, 2016 at 12:12

Ashique's user avatar

AshiqueAshique

3451 silver badge8 bronze badges

1

eprivalov

css

  • CSS

Есть ли такой псевдоэлемент CSS :first-word?

Пытаюсь использовать, но не срабатывает в Google Chrome 40.0.2214.115 m (64-bit)


  • Вопрос задан

    более трёх лет назад

  • 11561 просмотр



4

комментария

  • Неужели вам проще зайти на тостер, задать вопрос и ждать, пока вам ответят, чем зайти в гугл, вбить ваш вопрос и в 1-м же результате поиска прочитать ответ на него?

  • eprivalov

  • Евгений Привалов: вы так и не попытались погуглить, я вчера погуглил за вас, и вот то, что по вашей ссылке — реализация на js, велосипед, хак, и НЕ псевдоэлемент CSS

  • luckyluck

    А я начал гуглить, чтобы самому, без чьей либо помощи, найти ответ, и первым в выдаче гугла был именно этот вопрос на тостере(((

Пригласить эксперта


Ответы на вопрос 2

isqua

Alex

@isqua

Научу HTML, CSS, JS, BEM и Git

Нет, такого псевдо-элемента нет. Если хотите выделить первое слово, оберните его в тег.


Похожие вопросы


  • Показать ещё
    Загружается…

14 апр. 2023, в 08:46

30000 руб./за проект

14 апр. 2023, в 08:26

15000 руб./за проект

14 апр. 2023, в 08:07

1000 руб./за проект

Минуточку внимания

Недавно спрашивали, как средствами CSS сделать динамическое выделение первого слова в тексте. Оказалось, не всё так просто.

Первое, что приходит в голову — воспользоваться псевдоклассом :first-word. Однако, такого псевдокласса не существует. Получается, задача решения не имеет.

Не всё так грустно — первое слово в тексте можно поймать и выделить с помощью PHP или JavaScript. Об этих двух способах я сегодня и расскажу.

Каким образом вообще меняется стиль текста в HTML?

Для этого текст оборачивается в какой-нибудь тег. Можно присвоить класс или айди, чтобы точнее к нему прицелиться. Мы обойдемся без классов и в качестве примера возьмем заголовок H1 с тегом span внутри, и зададим ему такой стиль:

h1 span {
color: red;
}

Т.е. текст в заголовках H1, обернутый в span, будет красного цвета.

Теперь наша задача сводится к тому, чтобы вычленить из заголовка первое слово и обернуть его в тег span.

Сделаем это сначала на PHP, а потом на JavaScript.

PHP

На PHP задача решается очень просто с помощью строковых функций.

Допустим у нас есть некая переменная $title, содержащая искомый текст.

$title = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.';

Для решения задачи воспользуемся функцией explode(), которая возвращает массив строк, полученных разбиением строки с помощью разделителя. В нашем случае разделителем будет являться первый пробел.

$title = explode(" ", $title, 2);
echo '<span>' . $title[0] . '</span> ' . $title[1];

В результате получим:

<span>Lorem</span> ipsum dolor sit amet, consectetur adipisicing elit.

Теперь тегу span можно задать нужный стиль.

JavaScript

С ванильным JavaScript вряд ли кто-то захочет связываться, а вот на jQuery задача решается ещё проще, чем на PHP.

Код такой:

$(document).ready(function(){
 $('h1').each(function(){
  var title = $(this);
  title.html( title.text().replace(/(^w+)/,'<span>$1</span>') );
 });
});

Скрипт находит все заголовки H1 на странице и оборачивает первое слово внутри их тегом span.

Не забудьте подключить jQuery.

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

В результате первое слово всех заголовков H1 будет красного цвета, как и в примере с PHP.

Взяв за основу эти решения, можно пойти дальше и усложнить их до нужного результата. А про CSS обязательно расскажу, как только найдётся нормальное решение.

In this tutorial, I’m going to show you how you can style the first letter of a word, the first word of a paragraph, the first line of a paragraph and the first paragraph on a page.

Style-First-Letter-Word-Line-Paragraph

Style the first letter

To style the first letter of a word, we can use the pseudo-element, p::first-letter: The css code below will make the first letter of each paragraph to have a size of 28 pixels.

p::first-letter { font-size:28px; }

Style the first word

To style the first word of a paragraph, we need to use some jquery code, since we don’t have a pseudo-element for this one. Here’s how you can accomplish it:

$('p').each(function() {
    var word = $(this).html();
    var index = word.indexOf(' ');
    if(index == -1) {
        index = word.length;
    }
    $(this).html('<span class="first-word">' + word.substring(0, index) + '</span>' + word.substring(index, word.length));
});

And now we can simply use the .first-word class to style the first word of each paragraph:

.first-word { font-style:italic; }

Style the first line

To style the first line of a paragraph, is easy, since we have a pseudo-element for this:

p::first-line{ color:red; }

Style the first paragraph

And again, we don’t have a pseudo-element for this one, so we need to use a little bit of jquery:

$("p:first").addClass("first-paragraph");

And now we can use the .first-paragraph to style it:

.first-paragraph { background-color:#BDAA28; }

I hope this tutorial helped you learn how to Style First Letter, Word, Line and Paragraph with CSS and jQuery, if so, don’t forget to follow me on twitter @andornagy so you don’t miss out on other awesome tutorials like this!

Предельно простой способ выделить первое слово в строке или текстовом блоке HTML, используя CSS и jQuery.

Что бы выделить, в принципе, любой кусочек в текстовой строке в HTML-разметке (букву, слово, фразу) можно воспользоваться тегом <span>. Достаточно просто обернуть требуемый участок текста этим тегом, а в таблице стилей CSS прописать необходимое форматироваие текста – вот собственно, и все. Например, HTML и CSS код для заголовка с выделенным первым словом будет выглядеть примерно так:

HTML

<h2><span>Текст</span> заголовка с выделением</h2>

CSS

h2 {color: darkgrey}
h2 span {color: red}

В результате для темно-серого заголовка первое слово будет выделено красным цветом. Таким образом можно задать совершенно любое формирование для заданного участка текста. Конечно, если такая необходимость возникает разово-эпизодически, то конструкцию <span>…</span> можно и ручками прописать, но если дело требует регулярного использования, например, во всех заголовках или элементах списка, то тут нужен способ как-то решить это автоматизированно-технически.

Для выделения первого символа или первого дочернего элемента в CSS существуют соответствующие псевдоклассы :firts-letter и :firts-child, а вот именно для выделения первого слова пока не внедрили, что-то наподобие :firts-word. И что же делать? На выручку конечно же приходит jQuery!

Совсем коротенький java-скрипт можно прописать прямо в теле страницы или в отдельном js-файле, подключив через тег <script>

$(document).ready(function(){
 $("h2").each(function () {
  this.innerHTML = this.innerHTML.replace( /^(.+?)s/, "<span>$1</span> " );
 });
});

По сути скрипт, в каждом заданном элементе находит в начале строки последовательность символов, отделенную пробелом, и заменяет на саму себя с добавлением нужных нам тегов + пробел.

В результате работы скрипта, в каждом заголовке 2-го уровня H2 первое слово будет аккуратно автоматически обернуто тегом <span>…</span>. Можно комбинировать несколько селекторов в один с помощью запятой – jQuery выберет все элементы, которые соответствуют любому из селекторов, например, для применения ко всем заголовкам уровней с 1-го по 3-й вторая строчка будет выглядеть таким образом:

$("h1,h2,h3").each(function () {

Если вам требуется сделать выделение для повторяющихся элементов, например, конкретного отдельного списка, то в качестве селектора можно указать тег родительского элемента с заданным классом:

HTML

<ul class="f_word">
 <li>Перый элемент списка
 <li>Второй элемент списка
 <li>Третий элемент списка
</ul>

CSS

.f_word li span {
 color: red;
 font-weight: bold;
}

jQuery

…
$('.f_word li').each(function () {
…

В результате должен получится такой список, где первое слово будет иметь жирное начертание и красный цвет.

Реальный пример работы скрипта можно увидеть на одном из подготовленных наших сайтов.

Просмотры: 7 790

Понравилась статья? Поделить с друзьями:
  • First word from string php
  • First word from jesus
  • First word for kids
  • First word for baby
  • First word ever spoken