Как сделать текст в строчку html
Перейти к содержимому

Как сделать текст в строчку html

  • автор:

How can I force div contents to stay in one line with HTML and CSS?

How could I force the string to stay in one line (i.e., to be cut in the middle of "Overflow")?

I tried to use overflow: hidden , but it didn’t help.

Peter Mortensen's user avatar

11 Answers 11

Peter Mortensen's user avatar

Bazzz's user avatar

Use white-space:nowrap and overflow:hidden

In your CSS section, use white-space: nowrap; .

Peter Mortensen's user avatar

Rob Agar's user avatar

gogaz's user avatar

I made a fiddle:

RobAgar pointed out white-space:nowrap .

A couple of things here: You need overflow: hidden if you don’t want to see the extra characters poking out into your layout.

Also, as mentioned, you could use white-space: pre (see EnderMB), keeping in mind that pre will not collapse white space whereas white-space: nowrap will.

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

Всем привет, делал домашку на курсе, нужно сделать карточку товара, но столкнулся с проблемой:
Никак не получается сделать картинку и текст в одной строчке, как на приложенном фото
5fa1745a8ee2e104347020.jpeg
У меня же выходит вот так 5fa1748e9c71a435359447.png
Вот код
HTML

white-space

The white-space CSS property sets how white space inside an element is handled.

Try it

The property specifies two things:

  • Whether and how white space is collapsed.
  • Whether lines may wrap at soft-wrap opportunities.

Note: To make words break within themselves, use overflow-wrap , word-break , or hyphens instead.

Syntax

The white-space property is specified as a single keyword chosen from the list of values below.

Values

Sequences of white space are collapsed. Newline characters in the source are handled the same as other white space. Lines are broken as necessary to fill line boxes.

Collapses white space as for normal , but suppresses line breaks (text wrapping) within the source.

Sequences of white space are preserved. Lines are only broken at newline characters in the source and at <br> elements.

Sequences of white space are preserved. Lines are broken at newline characters, at <br> , and as necessary to fill line boxes.

Sequences of white space are collapsed. Lines are broken at newline characters, at <br> , and as necessary to fill line boxes.

The behavior is identical to that of pre-wrap , except that:

  • Any sequence of preserved white space always takes up space, including at the end of the line.
  • A line breaking opportunity exists after every preserved white space character, including between white space characters.
  • Such preserved spaces take up space and do not hang, and thus affect the box’s intrinsic sizes (min-content size and max-content size).

The following table summarizes the behavior of the various white-space values:

New lines Spaces and tabs Text wrapping End-of-line spaces End-of-line other space separators
normal Collapse Collapse Wrap Remove Hang
nowrap Collapse Collapse No wrap Remove Hang
pre Preserve Preserve No wrap Preserve No wrap
pre-wrap Preserve Preserve Wrap Hang Hang
pre-line Preserve Collapse Wrap Remove Hang
break-spaces Preserve Preserve Wrap Wrap Wrap

Note: There is a distinction made between spaces and other space separators. These are defined as follows:

Spaces (U+0020), tabs (U+0009), and segment breaks (such as newlines).

other space separators

All other space separators defined in Unicode, other than those already defined as spaces.

Where white space is said to hang, this can affect the size of the box when measured for intrinsic sizing.

Collapsing of white space

The CSS Text specification contains a Collapsing and Transformation section that precisely defines what «white space is collapsed» means, including an example with an illustration. Usually, it means reducing sequences of multiple white-space characters down to a single space character — though in some cases it means reducing them to no character (the empty string).

CSS: элементы в строку

Верстка

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

  1. Использовать display: inline-block
  2. Использовать float: left/right

Рассмотрим каждый из них.

CSS свойство display: inline-block

Данное свойство определяет элемент как строчно-блочный, другими словами выстраивает элементы в строку. Важно понимать как работает это свойство, поэтому давайте рассмотрим на практике. Сделаем 3 блока внутри родительского и расположим их в одну линию. Вот что получилось:

css свойство inline-block

HTML разметка выглядит следующим образом:

Как видно на изображении я добавил свойства background и border, чтоб наглядно видеть происходящее на странице. Обязательно задаем всем элементам height иначе оно будет равно 0 по умолчанию и мы ни чего не увидим. Трем блокам .child задаем display: inline-block и width: 30%.

ВНИМАНИЕ! Если не установить свойство width, блоки примут по умолчанию значение ширины всей страницы и от свойства display не будет ни какого толку.

Важно понимать что элементы встанут в одну линию если для них обоих (или более) будет задано свойство display: inline-block при этом между ними не будет других элементов, с отличным от данного, свойством. Если попробуем изменить класс для блока .child находящегося по середине, тем самым убрав все стили, то увидим что все элементы выстроились в ряд.

CSS свойство float: left или float: right

Аналогичное по результату inline-block, но отличное по принципам работы свойство float — в переводе с английского означает — обтекание. Давайте попробуем убрать из предыдущего примера

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

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