The title of the document

How to Vertically Align a Text Next to the Image

If you want your Website to look beautiful and harmonious, then this snippet is for you. It will help you to learn how to align text next to an image vertically. Let’s dive in and learn to do it together!

Create HTML

html> html>   body> div div img src="https://i.pinimg.com/originals/26/ea/fc/26eafc0b14488fea03fa8fa9751203ff.jpg">
">

Paris is one of the most beautiful cities in France.

Add CSS

  • Put the display property and choose the «flex» value. It will represent the element as a block-level-flex container.
  • Use the align-items property with the «center» value to place the items at the center of the container.
  • Set the justify-content property to «center».
  • Put the image’s maximum width to 100% with the max-width property.
  • Set the flex-basis property of the «image» class to specify the initial main size of your image.
  • Choose the font size of your text with the help of the font-size property.
  • Use the padding-left property to set the padding space on the text’s left side.
.container < display: flex; align-items: center; justify-content: center > img < max-width: 100% > .image < flex-basis: 40% > .text < font-size: 20px; padding-left: 20px; >

You can style the text with other properties, such as color, text-alignment, text-decoration, text-transform, text-shadow and so on.

Читайте также:  Display errors and warnings php

Now let’s put the code parts together and see the result.

Example of vertically aligning a text next to the image:

html> html> head> title>The title of the document title> style> .container < display: flex; align-items: center; justify-content: center > img < max-width: 100% > .image < flex-basis: 40% > .text < font-size: 20px; padding-left: 20px; > style> head> body> div class="container"> div class="image"> img src="https://i.pinimg.com/originals/26/ea/fc/26eafc0b14488fea03fa8fa9751203ff.jpg"> div> div class="text"> h1>Paris is one of the most beautiful cities in France. h1> div> div> body> html>

Result

Paris

Paris is one of the most beautiful cities in France.

You can style the text with other properties, such as font, color, text-decoration, text-shadow and so on.

Example of styling a vertically aligned text:

html> html> head> title>The title of the document title> style> .container < display: flex; align-items: center; justify-content: center > img < max-width: 100% > .image < flex-basis: 70%; order: 2; > .text < color: #CD5C5C; padding-left: 20px; font: italic 10px "Fira Sans", serif; > style> head> body> div class="container"> div class="image"> img src="https://cdn.londonandpartners.com/visit/general-london/areas/river/76709-640x360-houses-of-parliament-and-london-eye-on-thames-from-above-640.jpg"> div> div class="text"> h1>London is the capital and largest city of England. h1> div> div> body> html>

Источник

Позиционирование текста на картинке в CSS

Позиционирование текста на картинке в CSS

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

Нам надо рядом с каждым овощем, на иллюстрации ниже, подписать его название. Задача вроде бы простая, но поверьте, может свести с ума любого начинающего веб-мастера.

Позиционирование текста на картинке в CSS.

Я умышленно для примера взял большую картинку 1280×733, чтобы заодно показать, как её адаптировать под разные разрешения экранов. Уже прошли те времена, когда достаточно было научиться верстать только под десктопные разрешения. Делая верстку, следует сразу позаботиться об адаптивности.

HTML-разметка

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

vegetables

Лук

Картошка

Морковка

После сделанной HTML-разметке, мы видим только фрагмент картинки и текст, оказавшийся под картинкой. Знакомая картина, не правда ли?

Позиционирование текста на картинке в CSS.

Картинка разъехалась на все свои немаленькие пиксели и появилась горизонтальная полоса прокрутки, но к счастью это легко исправить, задав ширину картинке 100%, тем самым сделав её адаптивной. Хотя бы одну проблему решили.

Позиционирование текста на картинке в CSS.

CSS-стили

В стилях контейнера, ключевым будет свойство position: relative. Этим мы меняем правила и просим вести отсчет координат не от верхнего левого угла окна браузера, а от угла контейнера, который является родителем для всех вложенных в него элементов и занимает 90% окна.

.container width: 90%;
position: relative;
text-align: center;
color: #000;
font-family: arial black;
font-size: 250%;
>

Дальше будем позиционировать надписи, просто подбирая в системе X/Y нужные координаты, делать подбор удобно в Chrome / Инструменты разработчика, копируя и вставляя код в файл со стилями.

.left position: absolute;
top: 26%;
left: 6%;
>

.center position: absolute;
top: 17%;
left: 42%;
>

.right position: absolute;
top: 1%;
right: 27%;
>

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

Позиционирование текста на картинке в CSS.

Медиа-запросы

На разрешении равным или меньше 768 пикселей, уменьшить размер шрифта до 150%. Откуда мы узнали, что надо уменьшать именно на 768 пикселях? Через инспектор кода, мы увидели, на какой отметке текст наскакивает на соседние элементы.

@media screen and (max-width: 768px) .container font-size: 150%;
>
>

Одного запроса оказалось недостаточно, уменьшили размер текста и на 470 пикселях.

@media screen and (max-width: 470px) .container font-size: 90%;
>
>

Конечный результат

Позиционирование текста на картинке в CSS.

Посмотрите на реальной странице, как прекрасно смотрится текст на картинке на разных разрешениях.

Демонстрация.

Из данного видео-курса «HTML5 и CSS3 с Нуля до Гуру»вы получите систематизированные знания о том, как делаются сайты, на простых примерах.

Создано 19.10.2018 10:22:00

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

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

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

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

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    How to position Text Over an Image using CSS

    Web Developers build websites with rich aesthetics for better engagement and user delight. One such visual aspect that developers incorporate while developing any webpage is positioning text over an image. Keeping responsiveness into consideration, it is important to ensure that the text remains consistent even when the image resizes itself due to its responsive behavior.

    This article discusses the step by step methods to Position Text over Image for all Orientations, the method to Position Text over Image for Responsive Images, and how to Test the Responsiveness of the resulting image with text.

    How to position Text over an Image using CSS (All the Orientations)

    An easy and straightforward way to position text over an image is by using CSS. The idea behind its implementation is to put all the elements, including the image and the text element, inside the same container div in the HTML file. After that, you have to apply the CSS on each element in the CSS section of the project.

    Step 1: Create an HTML file and put image and text elements in one parent container div, as seen below.

    Image on which Text is positioned using CSS

         
    Landscape
    Centered
    Bottom Left
    Top Left
    Top Right
    Bottom Right

    Step 2: Positioning text on the image using CSS

    Once all the elements are placed, you just have to apply CSS on the elements to align them as intended. In this step, applying CSS for the elements to position them in several orientations over the image, such as bottom-left, bottom-right, and more.

    img < height: 100%; width: 100%; >.parentContainer < position: relative; text-align: center; color: white; >.bottom-left < position: absolute; bottom: 10px; left: 15px; >.top-left < position: absolute; top: 10px; left: 15px; >.top-right < position: absolute; top: 10px; right: 15px; >.bottom-right < position: absolute; bottom: 10px; right: 15px; >.centered

    The resulting image photo.jpg looks like the below after positioning text over it in different orientations.

    Image after positioning Text over it using CSS

    How to position text over a Responsive Image

    Responsive webpages are necessary from a user experience standpoint. It also improves the overall SEO and enhances content visibility on the web. Responsive images are vital for a responsive website, and while positioning text over a Responsive Image, it is essential to ensure that the text alignment remains intact without impacting the responsiveness of the image.

    Step 1: Create an HTML file

    In the HTML file, use the figure tag to initialize the photo in the document. The reason behind implementing the figure and figcaption tags in the HTML is to leverage the Search Engine Optimization (SEO) of the document.

    Responsive Image on which text is positioned using css

         
    background
    This is the text over image

    Step 2: Positioning text on the image using CSS

    To solve the issue of responsiveness, width is added as 100%. Moreover, setting the position of the figcaption as absolute will keep the text to the nearest positioned parent element. Also, you can apply more CSS to further enhance your text while positioning it over the image.

    .image img < width: 100%; height: 100%; >.image < position: relative; >.image figcaption

    The resulting responsive image picture.jpg looks like the below after positioning text over it.

    Responsive Image after positioning Text over it using CSS

    How to Test the Responsiveness of Images with Text

    Now that you have created images that contain text over it, it is necessary that the images being used in the webpage are responsive. This means that text and images do not break their connection even if the webpage is rendered on several devices. Hence, it is always advisable to test the responsive images before making them live.

    Using BrowserStack Responsive to check the responsiveness of images with text on several devices.

    Free Responsive Test on Commonly Used Resolutions

    Try testing the responsiveness of your website on real devices.

    Follow the easy steps below to test your responsive image on BrowserStack Responsive:

    Step 1: Open BrowserStack Responsive Dashboard and enter the URL of the webpage containing the responsive image. If you have created a website on your local machine, you must host your website to test its responsiveness on BrowserStack Responsive.

    Test the Responsiveness of Images with Text positioned over it

    Step 2: To check responsiveness, click Check.

    Step 3: The user can check how the site appears on a certain device after choosing it.

    Select Devices to Test the Responsiveness of Images with Text positioned over it

    Positioning text over an image using CSS is an easy yet necessary approach one should keep in mind during development to keep the responsiveness of the image intact. This can be easily achieved with the help of several CSS properties. CSS properties to position text over an image in several locations of the image, such as the center, and bottom, are useful for positioning text images. While. HTML features such as using Figure and Figcaption are further useful in maintaining the SEO and overall structure of the webpage.

    However, it is essential to test the responsiveness of the image after positioning text over it. There’s no way easier than BrowserStack’s Free Responsive Checker Tool, which allows testing the webpage on multiple real devices of choice spanning across different screen sizes and resolutions.

    Источник

    Оцените статью