I have the below message (slightly changed):
«Enter the competition by January 30, 2011 and you could win up to
$$$$ — including amazing summer trips!»
I currently have:
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
formatting the text string, but want to change the color of «January 30, 2011» to #FF0000 and «summer» to #0000A0.
How do I do this strictly with HTML or inline CSS?
Sam R.
15.9k11 gold badges68 silver badges122 bronze badges
asked Jan 7, 2011 at 5:38
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
Enter the competition by
<span style="color: #ff0000">January 30, 2011</span>
and you could win up to $$$$ — including amazing
<span style="color: #0000a0">summer</span>
trips!
</p>
Or you may want to use CSS classes instead:
<html>
<head>
<style type="text/css">
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
.date {
color: #ff0000;
}
.season { /* OK, a bit contrived... */
color: #0000a0;
}
</style>
</head>
<body>
<p>
Enter the competition by
<span class="date">January 30, 2011</span>
and you could win up to $$$$ — including amazing
<span class="season">summer</span>
trips!
</p>
</body>
</html>
answered Jan 7, 2011 at 5:41
JacobJacob
77.1k24 gold badges147 silver badges228 bronze badges
3
You could use the HTML5 Tag <mark>
:
<p>Enter the competition by
<mark class="red">January 30, 2011</mark> and you could win up to $$$$ — including amazing
<mark class="blue">summer</mark> trips!</p>
And use this in the CSS:
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
mark.red {
color:#ff0000;
background: none;
}
mark.blue {
color:#0000A0;
background: none;
}
The tag <mark>
has a default background color… at least in Chrome.
bad_coder
10.8k20 gold badges44 silver badges68 bronze badges
answered Dec 14, 2012 at 23:58
5
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>
The span elements are inline an thus don’t break the flow of the paragraph, only style in between the tags.
answered Jan 7, 2011 at 5:41
Damien-WrightDamien-Wright
7,2064 gold badges27 silver badges23 bronze badges
use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>
answered Jan 7, 2011 at 5:41
brian_dbrian_d
11.1k5 gold badges47 silver badges72 bronze badges
<font color="red">This is some text!</font>
This worked the best for me when I only wanted to change one word into the color red in a sentence.
Josh Lee
169k38 gold badges268 silver badges273 bronze badges
answered Sep 10, 2017 at 15:01
user8588011user8588011
2833 silver badges2 bronze badges
3
You can also make a class:
<span class="mychangecolor"> I am in yellow color!!!!!!</span>
then in a css file do:
.mychangecolor{ color:#ff5 /* it changes to yellow */ }
Muds
3,9645 gold badges32 silver badges51 bronze badges
answered Nov 20, 2015 at 15:34
JayMcpeZ_JayMcpeZ_
511 silver badge1 bronze badge
Tailor this code however you like to fit your needs, you can select text? in the paragraph to be what font or style you need!:
<head>
<style>
p{ color:#ff0000;font-family: "Times New Roman", Times, serif;}
font{color:#000fff;background:#000000;font-size:225%;}
b{color:green;}
</style>
</head>
<body>
<p>This is your <b>text. <font>Type</font></strong></b>what you like</p>
</body>
Wtower
18.4k11 gold badges106 silver badges80 bronze badges
answered Jun 19, 2016 at 11:23
You could use the longer boringer way
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p>
you get the point for the rest
answered Nov 17, 2015 at 19:51
In Uncategorized on January 11, 2012 by Your Friend Tagged: convert color, html, ms word
Perhaps you’ve created something in MS Word and would now like to use that same color using html, or vice versa. Here is a little tool you may find very useful: HEX to RGB Color Converter.
Accessing Font Color Codes in MS Word
To access the font color in MS Word, do the following:
- Open your document.
- Highlight the word where your color exists. (Will address tables further down.)
- Click on the arrow to the right of the A icon in the top tool bar of your document.
- Click on “More Colors”.
- Click on “Custom”. There you will find the 3 codes for RGB (red green blue). Use that using the tool to create an html color for that color. Or update that color using your existing html color code.
Accessing Background Color Codes in MS Word
If you are attempting to change a background color within a table or access the RGB color code rather than highlight a word do the following:
- Click in the cell where the color exists.
- Right click.
- Click on “Borders and Shading”.
- Click on the “Shading” tab above.
- Under “Fill”, click on the drop down arrow. (If no color exists, rather than show a color it will be show “No Color”.)
- Click on “More Colors” and find the codes for RGB.
Назад
Дата публикации: 14.04.2020
Просмотры: 1003
Бочка меда
СДО Collaborator умеет создавать учебные ресурсы из готового документа MS Word. Достаточно загрузить файл DOCX-формата, и система предложит преобразовать его в ресурс типа «Страница». Это существенно экономит время авторам ресурсов.
Порядок действий:
- Создать новый ресурс типа «Файл».
- Загрузить документ.
- После загрузки система спросит «Преобразовать файл в Ресурс-Страницу?» — соглашайтесь.
- Сохранить и просмотреть результат.
Результатом будет HTML-ресурс в виде одной страницы, которая быстро загружается и имеет все шансы идеально отображаться на любых устройствах — от десктопа до мобильного телефона.
СДО Collaborator умеет создавать учебные ресурсы из готового документа MS Word.
Ложка дегтя
Но преобразование подразумевает, что при верстке документа DOCX вы пользовались общепринятыми правилами и форматированием, которому существует прямая альтернатива в формате HTML. Если прямого соответствия не будет, то и результат преобразования не сможет соответствовать оригиналу.
Что получится из вашего документа, вы можете легко проверить на сервисах преобразования Word в HTML. Например, этих:
- Online HTML converter
- Word to HTML Converter Online. Convert Word to clean HTML — 4html.net
- WORD to HTML | DOC to HTML
Можно проверить, как сам MS Word справляется с преобразованием своего документа в формат HTML. Попробуйте команду «Файл» — «Сохранить как…» и выберите формат «Веб-страница с фильтром (.htm)».
Если результат будет адекватен оригиналу — то ваш документ отформатирован хорошо.
Абсолютного точного (или максимально близкого к нему) преобразования документа DOCX в другой формат можно добиться только преобразованием в PDF.
Но есть способы сделать документ так, чтобы он конвертировался в HTML без критических искажений.
Лучшие практики форматирования документа MS Word
1. Стили заголовков и текста
Используйте стандартные стили заголовков: «Заголовок», «Подзаголовок», «Заголовок 1», «Заголовок 2» и т.д.
Текст набирайте стандартным стилем — «Обычный».
2. Интервалы и отступы
Если нужно для абзацев изменить отступы, поменять интервал, шрифт — изменяйте в тексте. Можно изменять стили, но это не всегда работает.
3. Выравнивание текста
Обычно с этим проблем не бывает. Все преобразуется корректно.
4. Форматирование шрифта
Все обычные способы изменения шрифта — начертание, цвет, размер — будут хорошо преобразовываться.
5. Изменение типа шрифта
Шрифт сможет отобразиться правильно только в том случае, если на чужом компьютере будут установлены те же шрифты, что и у вас. Используйте «безопасные шрифты» (узнать больше про безопасные шрифты):
6. Списки
С простыми маркированными и нумерованными списками проблем не должно возникнуть. Иерархические списки тоже неплохо конвертируются, но будут отличия.
7. Вставка картинок
Корректно будут отображаться картинки, вставленные в текст как знак, а не как отдельный объект с возможностью обтекания. На всякий случай проверьте, что настроено в параметрах картинки «Размер и положение» — «Обтекание текстом», должно быть так:
Самый надежный способ — отдельная картинка в отдельном абзаце текста.
Никакие настройки обтекания картинки текстом не дадут хорошего результата. Картинки будут «убегать» со своих мест и игнорировать ваши настройки.
Единственный стабильный случай — это обтекание картинки текстом справа. Вставьте картинку первой в абзаце перед всем текстом и в настройках «Размер и положение» — «Обтекание текстом» выберите стиль обтекания «Квадрат» и обтекание текстом «Справа». Там же дополнительно можно настроить отступы от текста.
8. Изменение размера, оформления и параметров картинок
Вы можете изменять размеры картинок и экспериментировать с другими преобразованиями.
Как правило, простые изменения корректно переносятся в HTML. Но что-то особенное — вряд ли будет распознано правильно.
9. Таблицы
Таблицы конвертируются практически без ошибок.
Если нужно, чтобы таблица растягивалась на всю ширину страницы — установите для нее параметр «Автоподбор по ширине окна». В этом случае лучше делать таблицу как можно проще — без объединённых и разбитых ячеек, преобразование может быть неточным.
Итог
Волшебного средства, что точно преобразовывает любой DOCX в HTML, не существует. И не может быть. Слишком много специфических отличий у этих форматов.
Если вам важна скорость создания учебных ресурсов в СДО и их адаптивность к чтению с мобильных устройств — очищайте и упрощайте форматирование документов, конвертируйте в HTML. У вас будет быстрый и приемлемый результат.
Требуется точное соответствие документу? С этим лучше всего справляется преобразование в формат PDF. Но придется забыть про удобства чтения с экрана смартфона.
Есть время и вдохновение — изучайте верстку HTML документов с помощью правил Bootstrap его альтернатив Bootstrap Alternatives (Top 10 Best Frontend Frameworks).
P.S. У нас есть пример правильно подготовленного Word файла. Его можно брать как шаблон для своих документов. Пройдите на демо-портал LMS Collaborator в Каталог учебных заданий и заберите его по этой ссылке:
Просто взять и скачать.
P.S. Есть предложения, вопросы, замечания, идеи — пишите в комментарии.
Присоединяйтесь к нашему сообществу корпоративного обучения в Facebook и Linkedin, а также подписывайтесь на нашу e-learning рассылку, чтобы получить апрельскую скидку на использование LMS Collaborator по промокоду: LMS2020-04
The LMS Collaborator Team
Content Manager LMS Collaborator
Всі записи автора
Free online Text/Word to HTML converter with built-in code cleaning features with escapes or unescapes HTML tags.
Hypertext Markup Language (HTML) is the standard markup language for creating web pages and web applications. Web browsers receive HTML documents from a web server or from local storage and render the documents into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects such as interactive forms may be embedded into the rendered page. HTML provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets. Tags such as <img/> and <input/> directly introduce content into the page. Other tags such as <p> surround and provide information about document text and may include other tags as sub-elements. Browsers do not display the HTML tags, but use them to interpret the content of the page.
Escapes or unescapes an HTML
Convert special characters to HTML entities. Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with these conversions made.
The following characters are reserved in HTML and must be replaced with their corresponding HTML entities:
The translations performed are:
- ‘&’ (ampersand) becomes ‘&’
- ‘»‘ (double quote) becomes ‘"’
- «‘» (single quote) becomes ‘'’
- ‘<‘ (less than) becomes ‘<’
- ‘>’ (greater than) becomes ‘>’
What Is HTML? Hypertext Markup Language Basics Explained
HTML stands for HyperText Markup Language. HTML is the primary markup language found on the internet. Every HTML page has a series of elements that create the content structure of a web page or application. HTML provides the structure and content of a web page, and it is used in conjunction with other technologies like CSS and JavaScript to make websites dynamic and interactive.
HTML consists of a series of elements and tags, which are used to define the structure and content of a web page. For example, the title of a web page is typically defined using an <h1> tag, and paragraphs of text are defined using the <p> tag. HTML also includes tags for creating lists, links, images, tables, and many other types of content.
The three main parts of an element are:
- Opening tag – used to state where an element starts to take effect. The tag is wrapped with opening and closing angle brackets. For example, use the start tag
to create a paragraph.
- Content – this is the output that other users see.
- Closing tag – the same as the opening tag, but with a forward slash before the element name. For example, </p> to end a paragraph.
The combination of these three parts will create an HTML element:
<p> This is how you add a paragraph in HTML.</p>
Every HTML page uses these three tags:
- <html> tag is the root element that defines the whole HTML document.
- <head> tag holds meta information such as the page’s title and charset.
- <body> tag encloses all the content that appears on the page.
<html> <head> <!-- META INFORMATION --> </head> <body> <!-- PAGE CONTENT --> </body></html>
Other popular block-level tags include:
- Heading tags – these range from <h1> to <h6>, where heading h1 is largest in size, getting smaller as they move up to h6.
- Paragraph tags – are all enclosed by using the <p> tag.
- List tags – have different variations. Use the tag for an ordered list, and use for an unordered list. Then, enclose individual list items using the <li> tag.
HTML has evolved over the years, with new versions being introduced to add new capabilities and improve the language. The latest version of HTML is HTML5, which provides new elements and attributes, improved semantic elements, and better support for multimedia and other types of web-based content.
How To Use This Online WORD/Text to HTML Generator Tool?
The WORD/Text to HTML Generator we offer is user-friendly and provides a seamless experience for both professionals and beginners. No complex rules or technical know-how is required to utilize this service, making it accessible for everyone. The straightforward steps outlined below will assist you in using our tool to view HTML Code code online.
- Type or Paste your content in the input box provided on this tool. The tool allows its users to copy-paste code.
- The next step is to click the «Convert to HTML» button as per your requirement.
- As this button is pressed, the results are generated and displayed instantaneously.
- Use «HTML Escape» and «Unescape HTML» options to convert your output.
- After you have generated the HTML code, you can click on «Copy to Clipboard» or select all converted text and press «Control-C» to copy, and then «Control-V» to paste it back into your document.
- Alternatively, you can download generated HTML code to a text file by simply clicking on the «Download» button.
Useful Features of Our Online WORD/Text to HTML Generator
The Online WORD/Text to HTML Generator tool on our website comes equipped with exceptional features, making it the best online tool for generate text or HTML codes. The most notable features of our online utility are listed below.
Free and Simple to Use
The use of this tool comes at no cost, and it’s effortless to use. With the simple set of instructions provided, you’ll be able to view and run codes easily.
View and Verify HTML
You can now quickly view the output of any HTML code and test its validity with just one click.
Compatibility
This tool is a cloud-based utility and supported by all operating systems, including iOS, Android, Windows, and Mac OS, allowing you to access and use it for viewing HTML files from any device.
No Plugin Installation Needed
You can access this tool through the web browser of your device without having to install any plugins. This HTML viewer operates without the need for any plugins, making it convenient to use.
Speedy and Secure
The tool displays results on the user’s screen in mere seconds, and it’s a secure online utility that doesn’t save any data entered or uploaded by users in its databases.
Accessible from Everywhere
You can access our tool from anywhere in the world as long as you have an internet connection. Simply connect your device to the internet, and you’ll be able to use and access this code viewer.
Privacy of Users’ Data
At Onlinewebtoolkit, we offer a variety of online tools, including an WORD/Text to HTML Generator, and we take the privacy of our users’ data very seriously. With so many online scams, many people are concerned about their sensitive information being compromised when using online tools. However, our website provides a secure and safe tool that prevents hackers from accessing or intentionally sharing users’ information with third parties. The HTML code you input into our tool is only stored temporarily on the client side within your browser until the formatting process is complete. Once the results are displayed or you refresh or close the browser, your data is deleted from our site.
- Change the Color of One Word in a String of Text in HTML
- Change the Color of One Word in a String of Text in HTML Using Internal CSS
- Change the Color of One Word in a String of Text in HTML Using JavaScript
The main topic of this article is utilizing CSS to highlight or change the color of any particular word in a text. We’ll go over several techniques for implementing this feature.
We will learn to color a text using internal and inline CSS. Later, we’ll look at how to use JavaScript to implement the same functionality.
Change the Color of One Word in a String of Text in HTML
We commonly see on websites that a single word in a text has a different color than the others; of course, it captures the users’ attention. Let’s discuss how we can do the same on our web pages.
In the earlier versions of HTML, we had a <font>
tag that can be used to implement this feature like this:
<font color="red">Red</font>
But the tag is removed in HTML5 and is no longer supported. So, we will learn about an HTML <span>
tag to help us do the task.
The <span>
element is an inline container to mark up a section of a text or a section of a page. The id or class attribute of the <span>
tag allows simple styling with CSS and modifications with JavaScript.
The <span>
tag also allows us to apply inline styling, similar to the div
element. However, <span>
is an inline element, whereas div
is a block-level element.
Check the example below to understand this.
<html>
<body>
<p>Hello, I am
<span style="color: red">Red</span>
</p>
</body>
</html>
CSS’s color
property gives the text a specific color. There are many ways to specify the required color; in the above example, we select the color by its name.
HTML can recognize 16 color names which are black, white, grey, silver, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, and aqua. New browsers can recognize 140 CSS color names.
You can check all the HTML-recognized color names from here. As we mentioned, many other ways to specify the required color exist.
Let’s have a look at different methods.
RGB Colors
RGB stands for red, green, blue. It uses an additive color scheme in which the three primary colors, Red, Green, and Blue, are combined to create each color.
The red, green, and blue parameters each have a value between 0 and 255 that describes the color’s intensity. This indicates that there are 256 x 256 x 256 = 16,777,216 distinct colors.
For instance, rgb(255, 0, 0)
is rendered red because the color red is set to its greatest value, 255, while the other two colors, green and blue, are set to 0. Set all color parameters to zero like this rgb(0,0,0)
to display black.
You can see the RGB value of different colors from here.
<html>
<body>
<p>Hello, I am
<span style="color: rgb(241, 196, 15 )">Yellow</span>
</p>
</body>
</html>
RGBA Colors
RGBA colors are an extension of RGB colors, including an Alpha channel that determines a color’s opacity. The syntax for an RGBA color value is:
rgba (red, green, blue, alpha)
The value of the alpha parameter ranges from 0.0 (complete transparency) to 1.0 (full visibility). You can also use this property for the background colors, as sometimes we need different background colors with various opacity.
HEX Colors
Hex colors use hexadecimal values to represent colors from different color models. Hexadecimal colors are represented by the #RRGGBB
, where RR
stands for red, GG
for green, and BB
for blue.
The hexadecimal integers that specify the color’s intensity can range from 00
to FF
; an easy example is #0000FF
. Because the blue component is at its highest value of FF
while the red and green parts are at their lowest value of 00
, the color is entirely blue.
You can see the hex value of different colors from here.
<html>
<body>
<p>Hello, I am
<span style="color: #0000FF">Blue</span>
</p>
</body>
</html>
HSL Colors
HSL is an acronym that stands for Hue, Saturation, and Lightness. Let’s take a deeper look at each term.
- Hue: The hue ranges from 0 to 360 degrees on the color wheel. Red is 0; yellow is 60; green is 120; blue is 240, etc.
- Saturation: This quantity is measured as a percentage, with 100% denoting fully saturated (i.e., no shades of grey), 50% denoting 50% grey but with still-visible color, and 0% indicating entirely unsaturated (i.e., completely grey and color invisible).
- Lightness: This is also a percentage: 0% is black, and 100% is white. The amount of light we wish to give a color is expressed as a percentage, with 0% being black (where there is no light), 50% representing neither dark nor light, and 100% representing white (complete lightness).
The syntax for HSL color values is:
hsl(hue, saturation, lightness)
You can see the HSL value of different colors from here.
<html>
<body>
<p>Hello, I am
<span style="color: hsl(23, 97%, 50% )">Orange</span>
</p>
</body>
</html>
HSLA Colors
HSLA colors are an extension of HSL with an Alpha channel specifying a color’s opacity. An HSLA color value is determined with:
hsla(hue, saturation, lightness, alpha)
The value of the alpha parameter is a number having a range strictly between 0.0, which means fully transparent, and 1.0, which means not transparent.
Change the Color of One Word in a String of Text in HTML Using Internal CSS
We have seen in detail all the methods of giving color in CSS. We have been using inline CSS for everything up until this point.
However, inline CSS is not a suggested method because it is only tied to the element. We must rewrite much if we want the same functionality on different page regions.
So let’s color our text using Internal CSS, defined in the HTML <head>
tag inside a <style>
tag.
<html>
<head>
<title>CSS Color Property</title>
<style>
#rgb{
color:rgb(255,0,0);
}
#rgba{
color:rgba(255,0,0,0.5);
}
#hex{
color:#EE82EE;
}
#hsl{
color:hsl(0,50%,50%);
}
#hsla{
color:hsla(0,50%,50%,0.5);
}
#built{
color:green;
}
</style>
</head>
<body>
<h1>
Hello this is <span id="built">Built-in color</span> format.
</h1>
<h1>
Hello this is <span id="rgb">RGB</span> format.
</h1>
<h1>
Hello this is <span id="rgba">RGBA</span> format.
</h1>
<h1>
Hello this is <span id="hex">Hexadecimal</span> format.
</h1>
<h1>
Hello this is <span id="hsl">HSL</span> format.
</h1>
<h1>
Hello this is <span id="hsla">HSLA</span> format.
</h1>
</body>
</html>
Change the Color of One Word in a String of Text in HTML Using JavaScript
We can change the color of a specific word in a sentence using JavaScript. We need to give an ID to our <span>
tag and then get that element from JavaScript using document.getElementById(ID-name)
and call the style
property on it. Here’s how.
<html>
<body onload="myFunction()">
<p>Hello, I am <span id="color-text">Magenta.</span></p>
<script>
function myFunction() {
document.getElementById("color-text").style.color = "magenta";
}
</script>
</body>
</html>