Как вставить текст в картинку css
Перейти к содержимому

Как вставить текст в картинку css

  • автор:

Как наложить текст на картинку в html?

Или вариант что был предложен или воспользуйтесь position: absolute что бы поместить блок поверх другого.

14 фев 2018 в 4:25

4 ответа 4

Сортировка: Сброс на вариант по умолчанию

   Наука.ру - главная   

Космоинфо

Погрузись в космос вместе с нами!

Новости Вопросы Основная


Отслеживать
ответ дан 14 фев 2018 в 4:22
user176262 user176262

Попробуй задать как фоновое изображение через CSS/SASS.

.image < background: url('image/image1.png'); width: 320px; height: 280px; //размер условный >
 

Текст Текст Текст

Отслеживать
6,641 6 6 золотых знаков 30 30 серебряных знаков 52 52 бронзовых знака
ответ дан 28 июл 2019 в 17:05
Анна Панина Анна Панина
21 1 1 бронзовый знак

Вариант 1, с использованием position: absolute

.container < position: relative; >.container img < position: absolute; >.container p
 

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Itaque, nulla?

Вариант 2, с использованием background-image (нужно знать размеры блока)

.bg < background: url('https://d626yq9e83zk1.cloudfront.net/files/2017/12/26-770x425.jpg') center center no-repeat; width: 300px; height: 300px; >.bg span
 
Lorem ipsum dolor sit amet consectetur adipisicing elit. Assumenda, rerum.

Отслеживать
ответ дан 14 фев 2018 в 4:31
2,298 1 1 золотой знак 9 9 серебряных знаков 12 12 бронзовых знаков

* < margin: 0; padding: 0; box-sizing: border-box; >.wrapper < display: grid; gap: 10px; grid-template-columns: 1fr; >.container < display: grid; place-items: end center; >.container img < width: 100%; object-fit: cover; >.container p < position: absolute; font-size: 20px; color: #fff; margin: 10px 10px 20px; > 

Lorem ipsum dolor sit amet consectetur adipisicing elit. Accusamus, fugiat. A, ipsum architecto sit nihil minus tenetur mollitia sequi est nostrum laudantium praesentium doloremque blanditiis recusandae, dolorum assumenda sed qui perspiciatis dolores? Quidem, itaque suscipit rerum, cupiditate delectus nesciunt dignissimos vel, odio corporis exercitationem facere nihil modi ducimus quas fugit.

Отслеживать
67.9k 216 216 золотых знаков 77 77 серебряных знаков 219 219 бронзовых знаков
ответ дан 6 фев в 16:42
1 2 2 бронзовых знака

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

CSS: работа с текстом на изображениях

Вы можете встретить компонент пользовательского интерфейса, у которого есть текст над изображением. В некоторых случаях в зависимости от используемого изображения текст будет трудно прочитать. У этой проблемы есть несколько различных решений, таких как добавление градиента или затемнение изображения, наложение тени на текст и другие. Этот прием будет полезен не только frontend и веб-разработчикам, но и ui/ux-дизайнерам. Написать эту статью меня вдохновил твит от Эдди Османи, работающего над Google Chrome.

Здесь я рассмотрю различные подходы и решения этой проблемы, а также то, как передать пользовательский интерфейс фронтенд разработчику таким образом, чтобы гарантировать, что UI реализован в соответствии с макетом дизайна, поскольку некоторые детали в CSS можно легко упустить.

Как Spotify делает текст на изображениях более читабельным: наложение CSS с линейным градиентом. В наши дни более распространенный, но все же эффективный метод улучшения цветового контраста

Вступление

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

Слева без оверлея, справа с оверлеем.

Обратите внимание, что версия без наложения градиента читается плохо. Для пользователя это нехорошо. Чтобы решить эту проблему, нам нужно добавить слой под текстом так, чтобы текст читался легко. Добавление этого слоя может быть сложной задачей, и я видел многих, кто внедряет это решение, не принимая во внимание доступность.

Обзор возможных решений

Давайте посмотрим на возможные решения.

Есть решения, требующие большего внимания, — это градиентные решения. Почему? Потому что добавить слой градиента — это очень просто, но текст не будет удобным.

Решения

Наложение градиента

Вообще говоря, наложение градиента — это наиболее распространённое решение, позволяющее сделать текст на изображении более чётким. Учитывая это, я остановлюсь на нём немного подробнее.

При реализации наложения градиента у нас есть два варианта:

  • Использовать отдельный элемент для градиента (псевдоэлемент или пустой )
  • Применить градиент как фоновое изображение.

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

Элемент содержимого позиционируется абсолютно, его фоновым изображением служит градиент. Это означает, что размер градиента равен высоте элемента.

.card__content < position: absolute; /* other styles (left, top, right, and padding) */ background: linear-gradient(to top, rgba(0, 0, 0, 0.85), transparent); >

На первый взгляд может показаться, что градиент хорошо работает. Это не так. Я протестировал тот же градиент с большим количеством изображений, и вот результат.

Обратите внимание, что контраст между белым текстом и изображениями не всегда чёткий. Некоторые люди прочитают текст, но использовать такой градиент — огромная ошибка.

Причина в том, что градиент должен покрывать больше пространства по вертикали, поэтому должен быть выше. Если градиент равен размеру контента, он будет работать не во всех случаях. Чтобы решить эту проблему, мы можем использовать min-height, как показано ниже:

min-height к элементу .card__content.

Flexbox для перемещения содержимого вниз.

.card__content < position: absolute; /* other styles (left, top, right, and padding) */ display: flex; flex-direction: column; justify-content: flex-end; background: linear-gradient(to top, rgba(0, 0, 0, 0.85), transparent); >

Другое решение — большой padding-top, с ним не нужны min-height и flexbox.

.card__content

Обратите внимание на разницу между левой и правой карточками. Градиент больше по высоте.

Выглядит хорошо. Можем ли мы сделать лучше? Определённо да!

Смягчение градиента

Присмотревшись, вы заметите, где заканчивается градиент, то есть у него резкая граница.

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

Чтобы достичь плавности, в CSS нам нужно несколько границ перехода градиента, но на момент написания этой статьи в CSS нет нативного способа сделать несколько границ. Хорошая новость заключается в том, что рабочая группа CSS обсуждает возможность реализации нативного смягчения градиентов на CSS, но остаётся неясным, когда эту возможность внедрят.

К счастью, г-н Андреас Ларсен создал удобные плагины PostCSS и Sketch, которые помогают преобразовывать резкий градиент в более мягкий.

Вот градиент CSS для примера выше:

.card__content

Сравните карточки со смягчением градиента и без него.

Горизонтальные градиенты

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

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

background: linear-gradient( to right, hsl(0, 0%, 0%) 0%, hsla(0, 0%, 0%, 0.964) 7.4%, hsla(0, 0%, 0%, 0.918) 15.3%, hsla(0, 0%, 0%, 0.862) 23.4%, hsla(0, 0%, 0%, 0.799) 31.6%, hsla(0, 0%, 0%, 0.73) 39.9%, hsla(0, 0%, 0%, 0.655) 48.2%, hsla(0, 0%, 0%, 0.577) 56.2%, hsla(0, 0%, 0%, 0.497) 64%, hsla(0, 0%, 0%, 0.417) 71.3%, hsla(0, 0%, 0%, 0.337) 78.1%, hsla(0, 0%, 0%, 0.259) 84.2%, hsla(0, 0%, 0%, 0.186) 89.6%, hsla(0, 0%, 0%, 0.117) 94.1%, hsla(0, 0%, 0%, 0.054) 97.6%, hsla(0, 0%, 0%, 0) 100% );

Смешивание сплошного цвета и градиента

Я узнал об этом приёме на сайте Netflix. На домашней странице для незарегистрированного пользователя есть заголовок с большим фоновым изображением.

Мне это нравится, но он скрывает многие детали изображения. Используйте этот приём только в том случае, если изображение должно быть декоративным (не приносит реальных преимуществ конечному пользователю).

 

Unlimited movies, TV shows, and more.

Watch anywhere. Cancel anytime.

.hero:after

Вот наглядное объяснение того, как работает этот паттерн.

Наложение градиента и тень текста

Есть небольшая полезная деталь, которая может сделать текст поверх изображений ещё лучше. Всё дело в добавлении к тексту лёгкой тени. Даже когда заметить её нелегко, она может быть очень полезной, если изображение не загружается. Посмотрим на такой пример.

.whatever-text

Наложение градиента, тень текста и непрозрачность

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

.player__icon < opacity: 0.9; >.player__time

Что в этом нового? Значки и проигрыватель имеют непрозрачность в 90 %. Это помогает им смешаться с фоном под ними. Создаётся ощущение, что элементы управления вмешаны в изображение.

Кроме того, белая тень у белого текста — эффективный способ сделать текст чётче. Вы хотите доказательства того, что всё вышесказанное будет работать, даже если фон полностью белый? Ну, вот.

Текст и элементы интерфейса хорошо читаются, даже когда изображение полностью беое

Youtube делает то же самое со своими видео.

Вот что мне понравилось в подходе Youtube:

  • Тёмная рамка для каждого значка, чтобы он лучше выделялся.
  • Чёрная тень вместо белой для времени видео.

Радиальный градиент

Интересное решение, о котором я узнал от Netflix, — радиальный градиент. Вот как он работает:

  1. Установите основной цвет заднего фона.
  2. Поместите изображение в верхний правый угол с шириной 75 %.
  3. Наложение соответствует размеру и положению изображения.
.hero < background-color: #000; min-height: 300px; >.hero__image < position: absolute; right: 0; top: 0; width: 75%; height: 100%; object-fit: cover; >.hero:after

Тем не менее команда Netflix в качестве оверлея использовала изображение .png. Конкретной причины этого я не знаю. Может быть, дело в проблеме с кросс-браузерностью или что-то в этом роде: я не тестировал решение с радиальным градиентом.

Выбор удобного пользователю цвета наложения

Я покажу отличный инструмент, который помогает выбрать правильную непрозрачность наложения в зависимости от изображения. Посмотрите его на Codepen. Интересная задача — сделать градиент удобным.

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

Тестирование

Решение нельзя считать хорошим, пока оно не протестировано, верно? Один из способов, который я использую для проверки наложения градиента, — добавление белого фона ниже градиента. Если текст после этого читаемый, то градиент будет работать с любым изображением, а если нет, вам нужно настроить и улучшить его.

В приведённом выше примере я выбрал сплошной цвет под заголовком, а коэффициент контрастности составляет 4,74, такой коэффициент считается хорошим.

Работа с Firefox DevTools

Спасибо Гийсу Вейфейкену: он рассказал мне, что Firefox может тестировать цветовой контраст на градиентах. Это отличная функция.

Если хотите прокачать себя в веб-разработке, освоить специальность frontend-разработчика или стать настоящим Fullstack-универсалом — приходите учиться, а наши опытные менторы и внимательные кураторы помогут вам дойти до финала.

Узнайте, как прокачаться в других специальностях или освоить их с нуля:

  • Профессия Data Scientist
  • Профессия Data Analyst
  • Курс по Data Engineering

ПРОФЕССИИ

  • Профессия Fullstack-разработчик на Python
  • Профессия Java-разработчик
  • Профессия QA-инженер на JAVA
  • Профессия Frontend-разработчик
  • Профессия Этичный хакер
  • Профессия C++ разработчик
  • Профессия Разработчик игр на Unity
  • Профессия Веб-разработчик
  • Профессия iOS-разработчик с нуля
  • Профессия Android-разработчик с нуля

КУРСЫ

  • Курс по Machine Learning
  • Курс «Machine Learning и Deep Learning»
  • Курс «Математика для Data Science»
  • Курс «Математика и Machine Learning для Data Science»
  • Курс «Python для веб-разработки»
  • Курс «Алгоритмы и структуры данных»
  • Курс по аналитике данных
  • Курс по DevOps

Основы стилизирования текста и шрифта

В данной статье мы начнём путь к овладению стилизацией текста при помощи CSS. Мы подробно изучим основы стилизации текста и шрифта, такие как толщина, начертание, семейство, стенография, выравнивание текста и другие эффекты, а также рассмотрим междустрочный и межбуквенный интервалы.

Необходимые знания: Базовые компьютерные знания, Основы HTML (раздел Введение в HTML), основы CSS (раздел Введение в CSS).
Задача: Изучить основные свойства и техники, необходимые для стилизации текста на веб-страницах.

Что участвует в стилизации текста в CSS?

Как вы уже проверили в своей работе с HTML и CSS, текст внутри элемента выкладывается в поле содержимого элемента. Он начинается в левом верхнем углу области содержимого (или в правом верхнем углу, в случае содержимого языка RTL) и течёт к концу строки. Как только он достигает конца, он переходит к следующей строке и продолжает, затем к следующей строке, пока все содержимое не будет помещено в коробку. Текстовое содержимое эффективно ведёт себя как ряд встроенных элементов, размещённых на соседних строках и не создающих разрывы строк до тех пор, пока не будет достигнут конец строки, или если вы не принудите разрыв строки вручную с помощью элемента .

Примечание: если приведённый выше абзац оставляет вас в замешательстве, то не имеет значения — вернитесь и просмотрите нашу статью о модели коробки, чтобы освежить теорию модели коробки, прежде чем продолжить.

Свойства CSS, используемые для стилизации текста, обычно делятся на две категории, которые мы рассмотрим отдельно в этой статье:

  • Font styles: Свойства, влияющие на шрифт, применяемый к тексту, влияющие на то, какой шрифт применяется, насколько он велик, является ли он полужирным, курсивным и т. д.
  • Text layout styles: Свойства, влияющие на интервал и другие особенности компоновки текста, позволяющие манипулировать, например, пространством между строками и буквами, а также тем, как текст выравнивается в поле содержимого.

Примечание: имейте в виду, что текст внутри элемента все затронуты как одна единая сущность. Вы не можете выбирать и стилизовать подразделы текста, если вы не обернёте их в соответствующий элемент (например, или ), или использовать текстовый псевдоэлемент, такой как ::first-letter (выделяет первую букву текста элемента). first-line (выделяет первую строку текста элемента) или ::selection (выделяет текст, выделенный в данный момент курсором.)

Шрифты

Давайте сразу перейдём к рассмотрению свойств для стилизации шрифтов. В этом примере мы применим некоторые различные свойства CSS к одному и тому же образцу HTML, который выглядит следующим образом:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Color

The color (en-US) property sets the color of the foreground content of the selected elements (which is usually the text, but can also include a couple of other things, such as an underline or overline placed on text using the text-decoration (en-US) property).

color can accept any CSS color unit, for example:

p  color: red; > 

This will cause the paragraphs to become red, rather than the standard browser default black, like so:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Font families

To set a different font on your text, you use the font-family property — this allows you to specify a font (or list of fonts) for the browser to apply to the selected elements. The browser will only apply a font if it is available on the machine the website is being accessed on; if not, it will just use a browser default font. A simple example looks like so:

p  font-family: arial; > 

This would make all paragraphs on a page adopt the arial font, which is found on any computer.

Web safe fonts

Speaking of font availability, there are only a certain number of fonts that are generally available across all systems and can therefore be used without much worry. These are the so-called web safe fonts.

Most of the time, as web developers we want to have more specific control over the fonts used to display our text content. The problem is to find a way to know which font is available on the computer used to see our web pages. There is no way to know this in every case, but the web safe fonts are known to be available on nearly all instances of the most used operating systems (Windows, macOS, the most common Linux distributions, Android, and iOS).

The list of actual web safe fonts will change as operating systems evolve, but it’s reasonable to consider the following fonts web safe, at least for now (many of them have been popularized thanks to the Microsoft Core fonts for the Web initiative in the late 90s and early 2000s):

Name Generic type Notes
Arial sans-serif It’s often considered best practice to also add Helvetica as a preferred alternative to Arial as, although their font faces are almost identical, Helvetica is considered to have a nicer shape, even if Arial is more broadly available.
Courier New monospace Some OSes have an alternative (possibly older) version of the Courier New font called Courier. It’s considered best practice to use both with Courier New as the preferred alternative.
Georgia serif
Times New Roman serif Some OSes have an alternative (possibly older) version of the Times New Roman font called Times. It’s considered best practice to use both with Times New Roman as the preferred alternative.
Trebuchet MS sans-serif You should be careful with using this font — it isn’t widely available on mobile OSes.
Verdana sans-serif

Примечание: Among various resources, the cssfontstack.com website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage.

Примечание: There is a way to download a custom font along with a webpage, to allow you to customize your font usage in any way you want: web fonts. This is a little bit more complex, and we will be discussing this in a separate article later on in the module.

Default fonts

CSS defines five generic names for fonts: serif , sans-serif , monospace , cursive and fantasy . Those are very generic and the exact font face used when using those generic names is up to each browser and can vary for each operating system they are running on. It represents a worst case scenario where the browser will try to do its best to provide at least a font that looks appropriate. serif , sans-serif and monospace are quite predictable and should provide something reasonable. On the other hand, cursive and fantasy are less predictable and we recommend using them very carefully, testing as you go.

The five names are defined as follows:

Term Definition Example
serif Fonts that have serifs (the flourishes and other small details you see at the ends of the strokes in some typefaces) My big red elephant
sans-serif Fonts that don’t have serifs. My big red elephant
monospace Fonts where every character has the same width, typically used in code listings. My big red elephant
cursive Fonts that are intended to emulate handwriting, with flowing, connected strokes. My big red elephant
fantasy Fonts that are intended to be decorative. My big red elephant
Font stacks

Since you can’t guarantee the availability of the fonts you want to use on your webpages (even a web font could fail for some reason), you can supply a font stack so that the browser has multiple fonts it can choose from. This simply involves a font-family value consisting of multiple font names separated by commas, e.g.

p  font-family: "Trebuchet MS", Verdana, sans-serif; > 

In such a case, the browser starts at the beginning of the list and looks to see if that font is available on the machine. If it is, it applies that font to the selected elements. If not, it moves on to the next font, and so on.

It is a good idea to provide a suitable generic font name at the end of the stack so that if none of the listed fonts are available, the browser can at least provide something approximately suitable. To emphasise this point, paragraphs are given the browser’s default serif font if no other option is available — which is usually Times New Roman — this is no good for a sans-serif font!

Примечание: Font names that have more than one word — like Trebuchet MS — need to be surrounded by quotes, for example «Trebuchet MS» .

A font-family example

Let’s add to our previous example, giving the paragraphs a sans-serif font:

p  color: red; font-family: Helvetica, Arial, sans-serif; > 

This gives us the following result:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 

Font size

In our previous module’s CSS values and units article, we reviewed length and size units. Font size (set with the font-size property) can take values measured in most of these units (and others, such as percentages), however the most common units you’ll use to size text are:

  • px (pixels): The number of pixels high you want the text to be. This is an absolute unit — it results in the same final computed value for the font on the page in pretty much any situation.
  • em s: 1 em is equal to the font size set on the parent element of the current element we are styling (more specifically, the width of a capital letter M contained inside the parent element.) This can become tricky to work out if you have a lot of nested elements with different font sizes set, but it is doable, as you’ll see below. Why bother? It is quite natural once you get used to it, and you can use em to size everything, not just text. You can have an entire website sized using em , which makes maintenance easy.
  • rem s: These work just like em , except that 1 rem is equal to the font size set on the root element of the document (i.e. ), not the parent element. This makes doing the maths to work out your font sizes much easier, although if you want to support really old browsers, you might struggle — rem is not supported in Internet Explorer 8 and below.

The font-size of an element is inherited from that element’s parent element. This all starts with the root element of the entire document — — the font-size of which is set to 16 px as standard across browsers. Any paragraph (or another element that doesn’t have a different size set by the browser) inside the root element will have a final size of 16 px . Other elements may have different default sizes, for example an (en-US) element has a size of 2 em set by default, so it will have a final size of 32 px .

article> p>My paragraphp> article> 

You would need to set its em value to 20/24, or 0.83333333 em . The maths can be complicated, so you need to be careful about how you style things. It is best to use rem where you can, to keep things simple, and avoid setting the font-size of container elements where possible.

A simple sizing example

When sizing your text, it is usually a good idea to set the base font-size of the document to 10 px , so that then the maths is a lot easier to work out — required (r)em values are then the pixel font size divided by 10, not 16. After doing that, you can easily size the different types of text in your document to what you want. It is a good idea to list all your font-size rulesets in a designated area in your stylesheet, so they are easy to find.

Our new result is like so:

h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
html  font-size: 10px; > h1  font-size: 5rem; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

Font style, font weight, text transform, and text decoration

CSS provides four common properties to alter the visual weight/emphasis of text:

  • font-style : Used to turn italic text on and off. Possible values are as follows (you’ll rarely use this, unless you want to turn some italic styling off for some reason):
    • normal : Sets the text to the normal font (turns existing italics off.)
    • italic : Sets the text to use the italic version of the font if available; if not available, it will simulate italics with oblique instead.
    • oblique : Sets the text to use a simulated version of an italic font, created by slanting the normal version.
    • normal , bold : Normal and bold font weight
    • lighter , bolder : Sets the current element’s boldness to be one step lighter or heavier than its parent element’s boldness.
    • 100 – 900 : Numeric boldness values that provide finer grained control than the above keywords, if needed.
    • none : Prevents any transformation.
    • uppercase : Transforms all text to capitals.
    • lowercase : Transforms all text to lower case.
    • capitalize : Transforms all words to have the first letter capitalized.
    • full-width : Transforms all glyphs to be written inside a fixed-width square, similar to a monospace font, allowing aligning of e.g. Latin characters along with Asian language glyphs (like Chinese, Japanese, Korean).
    • none : Unsets any text decorations already present.
    • underline : Underlines the text.
    • overline : Gives the text an overline.
    • line-through : Puts a strikethrough over the text .

    Let’s look at adding a couple of these properties to our example:

    Our new result is like so:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

    Text drop shadows

    You can apply drop shadows to your text using the text-shadow property. This takes up to four values, as shown in the example below:

    text-shadow: 4px 4px 5px red; 

    The four properties are as follows:

    1. The horizontal offset of the shadow from the original text — this can take most available CSS length and size units, but you’ll most commonly use px ; positive values move the shadow right, and negative values left. This value has to be included.
    2. The vertical offset of the shadow from the original text; behaves basically just like the horizontal offset, except that it moves the shadow up/down, not left/right. This value has to be included.
    3. The blur radius — a higher value means the shadow is dispersed more widely. If this value is not included, it defaults to 0, which means no blur. This can take most available CSS length and size units.
    4. The base color of the shadow, which can take any CSS color unit. If not included, it defaults to black .
    Multiple shadows

    You can apply multiple shadows to the same text by including multiple shadow values separated by commas, for example:

    text-shadow: 1px 1px 1px red, 2px 2px 1px red; 

    If we applied this to the (en-US) element in our Tommy the cat example, we’d end up with this:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

    Примечание: You can see more interesting examples of text-shadow usage in the Sitepoint article Moonlighting with CSS text-shadow.

    Text layout

    With basic font properties out the way, let’s now have a look at properties we can use to affect text layout.

    Text alignment

    The text-align property is used to control how text is aligned within its containing content box. The available values are as follows, and work in pretty much the same way as they do in a regular word processor application:

    • left : Left-justifies the text.
    • right : Right-justifies the text.
    • center : Centers the text.
    • justify : Makes the text spread out, varying the gaps in between the words so that all lines of text are the same width. You need to use this carefully — it can look terrible, especially when applied to a paragraph with lots of long words in it. If you are going to use this, you should also think about using something else along with it, such as hyphens , to break some of the longer words across lines.

    If we applied text-align: center; to the (en-US) in our example, we’d end up with this:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; > 

    Line height

    The line-height property sets the height of each line of text — this can take most length and size units, but can also take a unitless value, which acts as a multiplier and is generally considered the best option — the font-size is multiplied to get the line-height . Body text generally looks nicer and is easier to read when the lines are spaced apart; the recommended line height is around 1.5 – 2 (double spaced.) So to set our lines of text to 1.6 times the height of the font, you’d use this:

    line-height: 1.6; 
    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; > h1 + p  font-weight: bold; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; line-height: 1.6; > 

    Letter and word spacing

    The letter-spacing and word-spacing properties allow you to set the spacing between letters and words in your text. You won’t use these very often, but might find a use for them to get a certain look, or to improve the legibility of a particularly dense font. They can take most length and size units.

    So as an example, we could apply some word- and letter-spacing to the first line of each element in our example:

    p::first-line  letter-spacing: 4px; word-spacing: 4px; > 

    Let’s add some to our example, like so:

    h1>Tommy the cath1> p>Well I remember it as though it were a meal ago. p> p> Said Tommy the Cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. Many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. Truly a wonder of nature this urban predator — Tommy the cat had many a story to tell. But it was a rare occasion such as this that he did. p> 
    html  font-size: 10px; > h1  font-size: 5rem; text-transform: capitalize; text-shadow: 1px 1px 1px red, 2px 2px 1px red; text-align: center; letter-spacing: 2px; > h1 + p  font-weight: bold; > p::first-line  letter-spacing: 4px; word-spacing: 4px; > p  font-size: 1.5rem; color: red; font-family: Helvetica, Arial, sans-serif; line-height: 1.6; letter-spacing: 1px; > 

    Other properties worth looking at

    The above properties give you an idea of how to start styling text on a webpage, but there are many more properties you could use. We just wanted to cover the most important ones here. Once you’ve become used to using the above, you should also explore the following:

    • font-variant (en-US): Switch between small caps and normal font alternatives.
    • font-kerning (en-US): Switch font kerning options on and off.
    • font-feature-settings (en-US): Switch various OpenType font features on and off.
    • font-variant-alternates (en-US): Control the use of alternate glyphs for a given font-face.
    • font-variant-caps (en-US): Control the use of alternate capital glyphs.
    • font-variant-east-asian (en-US): Control the usage of alternate glyphs for East Asian scripts, like Japanese and Chinese.
    • font-variant-ligatures : Control which ligatures and contextual forms are used in text.
    • font-variant-numeric : Control the usage of alternate glyphs for numbers, fractions, and ordinal markers.
    • font-variant-position (en-US): Control the usage of alternate glyphs of smaller sizes positioned as superscript or subscript.
    • font-size-adjust (en-US): Adjust the visual size of the font independently of its actual font size.
    • font-stretch (en-US): Switch between possible alternative stretched versions of a given font.
    • text-underline-position (en-US): Specify the position of underlines set using the text-decoration-line property underline value.
    • text-rendering (en-US): Try to perform some text rendering optimization.

    Text layout styles:

    • text-indent : Specify how much horizontal space should be left before the beginning of the first line of the text content.
    • text-overflow (en-US): Define how overflowed content that is not displayed is signaled to users.
    • white-space : Define how whitespace and associated line breaks inside the element are handled.
    • word-break : Specify whether to break lines within words.
    • direction : Define the text direction (This depends on the language and usually it’s better to let HTML handle that part as it is tied to the text content.)
    • hyphens : Switch on and off hyphenation for supported languages.
    • line-break : Relax or strengthen line breaking for Asian languages.
    • text-align-last : Define how the last line of a block or a line, right before a forced line break, is aligned.
    • text-orientation (en-US): Define the orientation of the text in a line.
    • overflow-wrap : Specify whether or not the browser may break lines within words in order to prevent overflow.
    • writing-mode : Define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow.

    Font shorthand

    Many font properties can also be set through the shorthand property font . These are written in the following order: font-style , font-variant (en-US), font-weight , font-stretch (en-US), font-size , line-height , and font-family .

    Among all those properties, only font-size and font-family are required when using the font shorthand property.

    A forward slash has to be put in between the font-size and line-height properties.

    A full example would look like this:

    font: italic normal bold normal 3em/1.5 Helvetica, Arial, sans-serif; 

    Active learning: Playing with styling text

    In this active learning session, we don’t have any specific exercises for you to do: we’d just like you to have a good play with some font/text layout properties, and see what you can produce! You can either do this using offline HTML/CSS files, or enter your code into the live editable example below.

    If you make a mistake, you can always reset it using the Reset button.

    div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;"> h2>HTML Inputh2> textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"> p>Some sample text for your delightp> textarea> h2>CSS Inputh2> textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"> p < >textarea > h2>Outputh2> div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">div> div class="controls"> input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;" /> div> div> 
    const htmlInput = document.querySelector(".html-input"); const cssInput = document.querySelector(".css-input"); const reset = document.getElementById("reset"); let htmlCode = htmlInput.value; let cssCode = cssInput.value; const output = document.querySelector(".output"); const styleElem = document.createElement("style"); const headElem = document.querySelector("head"); headElem.appendChild(styleElem); function drawOutput()  output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; > reset.addEventListener("click", function ()  htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); >); htmlInput.addEventListener("input", drawOutput); cssInput.addEventListener("input", drawOutput); window.addEventListener("load", drawOutput); 

    Test your skills!

    You’ve reached the end of this article, and already did some skill testing in our Active Learning section, but can you remember the most important information going forward? You can find an assessment to verify that you’ve retained this information at the end of the module — see Typesetting a community school homepage.

    This assessment tests all the knowledge discussed in this module, so you might want to read the other articles before moving on to it.

    Summary

    We hoped you enjoyed playing with text in this article! The next article will give you all you need to know about styling HTML lists.

    In this module

    • Fundamental text and font styling
    • Styling lists
    • Styling links
    • Web fonts
    • Typesetting a community school homepage

    Found a content problem with this page?

    • Edit the page on GitHub.
    • Report the content issue.
    • View the source on GitHub.

    This page was last modified on 3 авг. 2023 г. by MDN contributors.

    Your blueprint for a better internet.

    Добавление текста на фотографию

    Excel для Microsoft 365 Word для Microsoft 365 Outlook для Microsoft 365 PowerPoint для Microsoft 365 Excel 2021 Word 2021 Outlook 2021 PowerPoint 2021 Excel 2019 Word 2019 Outlook 2019 PowerPoint 2019 Excel 2016 Word 2016 Outlook 2016 PowerPoint 2016 Excel 2013 Word 2013 Outlook 2013 PowerPoint 2013 Excel 2010 Word 2010 PowerPoint 2010 Excel 2007 Word 2007 PowerPoint 2007 Еще. Меньше

    Вы можете использовать текстовое поле или объект WordArt для добавления текста поверх фотографии в Word, Outlook,PowerPoint или Excel.

    Текстовое поле над фотографией

    Если текст длиннее или не требует причудливого стиля, может подойти текстовое поле. Текст можно форматировать любым способом.

    Объект WordArt над фотографией

    Если текст краткий и вам нужен стилизованный внешний вид, аналогичный тому, который вы можете увидеть на открытке, то wordArt может быть лучшим вариантом.

    Какое приложение вы используете?

    Word или Outlook

    Добавление текста на фотографию с помощью надписи
    1. В документе щелкните место, куда вы хотите вставить фотографию.
    2. На вкладке Вставка в группе Иллюстрации нажмите кнопку Фигуры, а затем выберите пункт Новое полотно. Выберите полотно
    3. Щелкните полотно, а затем на вкладке Вставка в группе Иллюстрации нажмите кнопку Рисунки. Группа
    4. Найдите и дважды щелкните фотографию, которую вы хотите использовать, а затем щелкните за пределами полотна.
    5. На вкладке Вставка в группе Текст нажмите кнопку Текстовое поле, а затем выберите пункт Добавление надписи внизу меню.
    6. Введите текст, который будет отображаться в текстовом поле, а затем перетащите его в нужное место в верхней части рисунка.
    7. Чтобы изменить шрифт или стиль текста, выделите текст и выберите нужное форматирование в контекстном меню.
    8. Щелкните внешний край надписи и перетащите ее на фотографию.
    9. Убедитесь, что текстовое поле по-прежнему выбрано, а затем на вкладке Формат фигуры в группе Стили фигуры выполните следующие действия.
      1. Нажмите кнопку Заливка фигуры и выберите команду Нет заливки.
      2. Нажмите кнопку Контур фигуры и выберите пункт Нет контура.

      Группа

      Выберите

    10. Щелкните внешний край фотографии, нажмите и удерживайте нажатой клавишу CTRL, а затем щелкните край объекта WordArt, чтобы выбрать оба элемента.
    11. На вкладке Формат фигуры в группе Упорядочить выберите Группа >Группа.
    Добавление текста на фотографию с помощью WordArt
    1. В документе щелкните место, куда вы хотите вставить фотографию.
    2. На вкладке Вставка в группе Иллюстрации нажмите кнопку Фигуры, а затем выберите пункт Новое полотно. Выберите полотно
    3. Щелкните полотно, а затем на вкладке Вставка в группе Иллюстрации нажмите кнопку Рисунки. Группа
    4. Найдите и дважды щелкните фотографию, которую вы хотите использовать.
    5. На вкладке Вставка в группе Текст нажмите кнопку WordArt, выберите нужный стиль и введите текст.
    6. Щелкните внешнюю границу объекта WordArt, чтобы выбрать его, перетащите текст на фотографию и при необходимости поверните его под нужным углом.
    7. Щелкните внешний край фотографии, нажмите и удерживайте нажатой клавишу CTRL, а затем щелкните край объекта WordArt, чтобы выбрать оба элемента.
    8. На вкладке Формат рисунка в группе Упорядочить выберите Группа >группа. Выберите

    PowerPoint или Excel

    Добавление текста на фотографию с помощью надписи

    Выберите значение в группе

    1. Убедитесь, что вы вставили фотографию в файл.
    2. На вкладке Вставка в группе Текст нажмите кнопку Текстовое поле, щелкните рядом с рисунком и перетащите указатель, чтобы нарисовать надпись, а затем введите текст.
    3. Чтобы изменить шрифт или стиль текста, выделите текст, щелкните его правой кнопкой мыши и выберите в контекстном меню нужное форматирование.
    4. Щелкните внешнюю границу надписи, чтобы выбрать ее, перетащите текст на фотографию и при необходимости поверните его под нужным углом.
    5. Убедитесь, что текстовое поле по-прежнему выбрано, а затем на вкладке Формат фигуры в группе Стили фигуры выполните следующие действия.
      1. Нажмите кнопку Заливка фигуры и выберите команду Нет заливки.
      2. Нажмите кнопку Контур фигуры и выберите пункт Нет контура.

      Стили фигур

      Выберите

    6. Щелкните внешний край фотографии, нажмите клавишу CTRL, а затем щелкните край текстового поля, чтобы выбрать оба элемента.
    7. На вкладке Формат фигуры в группе Упорядочить выберите Группа >Группа.
    Добавление текста на фотографию с помощью WordArt
    1. Убедитесь, что вы вставили фотографию в файл.
    2. На вкладке Вставка в группе Текст нажмите кнопку WordArt, выберите нужный стиль и введите текст. Выберите значение в группе
    3. Щелкните внешнюю границу объекта WordArt, чтобы выбрать его, перетащите текст на фотографию и при необходимости поверните его под нужным углом.
    4. Щелкните внешний край фотографии, нажмите и удерживайте нажатой клавишу CTRL, а затем щелкните край объекта WordArt, чтобы выбрать оба элемента.
    5. На вкладке Формат фигуры в группе Упорядочить выберите Группа >Группа. Выберите

    Какое приложение вы используете?

    Word или Outlook

    Добавление текста на фотографию с помощью надписи
    1. В документе щелкните место, куда вы хотите вставить фотографию.
    2. На вкладке Вставка в группе Иллюстрации нажмите кнопку Фигуры, а затем выберите пункт Новое полотно. Выберите полотно
    3. Щелкните полотно, а затем на вкладке Вставка в группе Иллюстрации нажмите кнопку Рисунки. Группа
    4. Найдите и дважды щелкните фотографию, которую вы хотите использовать, а затем щелкните за пределами полотна.
    5. На вкладке Вставка в группе Текст нажмите кнопку Текстовое поле, а затем выберите пункт Добавление надписи внизу меню.
    6. Введите текст, который будет отображаться в текстовом поле, а затем перетащите его в нужное место в верхней части рисунка.
    7. Чтобы изменить шрифт или стиль текста, выделите текст и выберите нужное форматирование в контекстном меню.
    8. Щелкните внешний край надписи и перетащите ее на фотографию.
    9. Убедитесь, что надпись по-прежнему выбрана, а затем в разделе Средства рисования на вкладке Формат в группе Стили фигур сделайте следующее:
      1. Нажмите кнопку Заливка фигуры и выберите команду Нет заливки.
      2. Нажмите кнопку Контур фигуры и выберите пункт Нет контура.

      Группа

      Выберите

    10. Щелкните внешний край фотографии, нажмите и удерживайте нажатой клавишу CTRL, а затем щелкните край объекта WordArt, чтобы выбрать оба элемента.
    11. В разделе Средства рисования на вкладке Формат в группе Упорядочить выберите Группировать >группа.
    Добавление текста на фотографию с помощью WordArt
    1. В документе щелкните место, куда вы хотите вставить фотографию.
    2. На вкладке Вставка в группе Иллюстрации нажмите кнопку Фигуры, а затем выберите пункт Новое полотно. Выберите полотно
    3. Щелкните полотно, а затем на вкладке Вставка в группе Иллюстрации нажмите кнопку Рисунки. Группа
    4. Найдите и дважды щелкните фотографию, которую вы хотите использовать.
    5. На вкладке Вставка в группе Текст нажмите кнопку WordArt, выберите нужный стиль и введите текст.
    6. Щелкните внешнюю границу объекта WordArt, чтобы выбрать его, перетащите текст на фотографию и при необходимости поверните его под нужным углом.
    7. Щелкните внешний край фотографии, нажмите и удерживайте нажатой клавишу CTRL, а затем щелкните край объекта WordArt, чтобы выбрать оба элемента.
    8. В разделе Работа с рисунками на вкладке Формат в группе Упорядочить выберите Группировать >группу. Выберите

    PowerPoint или Excel

    Добавление текста на фотографию с помощью надписи

    Выберите значение в группе

    1. Убедитесь, что вы вставили фотографию в файл.
    2. На вкладке Вставка в группе Текст нажмите кнопку Текстовое поле, щелкните рядом с рисунком и перетащите указатель, чтобы нарисовать надпись, а затем введите текст.
    3. Чтобы изменить шрифт или стиль текста, выделите текст, щелкните его правой кнопкой мыши и выберите в контекстном меню нужное форматирование.
    4. Щелкните внешнюю границу надписи, чтобы выбрать ее, перетащите текст на фотографию и при необходимости поверните его под нужным углом.
    5. Убедитесь, что надпись по-прежнему выбрана, а затем в разделе Средства рисования на вкладке Формат в группе Стили фигур сделайте следующее:
      1. Нажмите кнопку Заливка фигуры и выберите команду Нет заливки.
      2. Нажмите кнопку Контур фигуры и выберите пункт Нет контура.

      Стили фигур

      Выберите

    6. Щелкните внешний край фотографии, нажмите клавишу CTRL, а затем щелкните край текстового поля, чтобы выбрать оба элемента.
    7. В разделе Средства рисования на вкладке Формат в группе Упорядочить выберите Группировать >группа.
    Добавление текста на фотографию с помощью WordArt
    1. Убедитесь, что вы вставили фотографию в файл.
    2. На вкладке Вставка в группе Текст нажмите кнопку WordArt, выберите нужный стиль и введите текст. Выберите значение в группе
    3. Щелкните внешнюю границу объекта WordArt, чтобы выбрать его, перетащите текст на фотографию и при необходимости поверните его под нужным углом.
    4. Щелкните внешний край фотографии, нажмите и удерживайте нажатой клавишу CTRL, а затем щелкните край объекта WordArt, чтобы выбрать оба элемента.
    5. В разделе Средства рисования на вкладке Формат в группе Упорядочить выберите Группировать >группа. Выберите

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *