Основные варианты решения проблемы переноса слов в css

White-space mapping to find opportunities

Having created these Offerings and Buying Centers in the account, DemandFarm generated an account of Landscape. This is how the account looked in the beginning, we had all the Offerings as the Columns and the Buying Centers as rows.  One can see Opportunities & Engagements at multiple places. The account was well placed then, but the revenue growth of the account had stagnated. Because of the standard offerings like Engineering Consulting, Enterprise Security, etc. which were less relevant now. So, the company introduced new Offerings. One such example is when DemandFarm acquired a big Salesforce competency shop enabling them to offer services around Salesforce practice.

The challenge was to make the account managers embrace this change and grow the existing platinum accounts which seemed stagnant. Then, Salesforce was configured as a new offering and started appearing on the account Landscape as the new column. Since this was a new Offering the account managers were made to think where this new Offering could be sold. Obviously, it cannot be sold to the existing Buying Centers and therefore two new Buying Centers were identified & created namely Sales and Marketing. The combination of these new Buying Centers & the new Offering became the focus area or the ‘white-spaces-analysis’ for growth. White space mapping helps you to map areas to grow your service or product.

After this, the Account Manager created a plan to grow business with the new offering in the new Buying Centers. While the old buying centers were not generating new business, the account manager was still able to plan for an additional $1 million in Marketing and another $1million in Sales Buying Centers.

A similar exercise in all strategic account management for all new offerings leads to an additional plan of $40million in 2017. They are well on their way to achieving $28 million of that plan.

There is a lot of power in simplicity and visualization. However, it should not be concluded as ‘easy’.

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

A Few Common Uses

Probably the most common reason to use the property is when applying it to a link that you don’t want to drop to the next line. Look at the screen capture below from the zaBox “confirm details” page:

The “read more” link has the (») character next to it, but because there wasn’t enough room, it dropped to the next line. This would have been avoided if the link had its property set to . The link would then naturally fall to the next line as a single unit, and wouldn’t be broken up. This point helps emphasize the fact that the property only affects the content inside the element to which it’s applied. So, while the link itself will drop to the next line, the text inside the link will not be separated via line breaks.

Another use for this property is when you want to prevent a row of inline boxes from wrapping to the next line. I mentioned this in a previous article discussing how to center multiple block-level elements on a single line.

Property Values

Value Description Play it
normal Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary. This is default Play it »
nowrap Sequences of whitespace will collapse into a single whitespace. Text will never wrap to the next line. The text continues on the same line until
a <br> tag is encountered
Play it »
pre Whitespace is preserved by the browser. Text will only wrap on line breaks. Acts like the
<pre> tag in HTML
Play it »
pre-line Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks Play it »
pre-wrap Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks Play it »
initial Sets this property to its default value. Read about initial Play it »
inherit Inherits this property from its parent element. Read about inherit

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

AirPods Pro

Можно найти наушники лучше AirPods в чём-то конкретном. Но в целом лучше обычных AirPods могут быть только AirPods Pro.

Хороший (что бы кто там ни говорил) звук для любых жанров и предпочтений. Достойный шумодав, который не напрягает мозг. Лёгкая посадка. Режим Прозрачности. Мгновенное подключение. 6 часов работы при маленьком кейсе. И куча новых фишек, которые появятся этой осенью вместе с iOS 14.

Купив AirPods Pro, точно не промахнётесь с выбором. Лишь бы в экосистеме Apple находились.

Цена: 17 990 рублей

P.S. Чем сами-то пользуетесь?

iPhones.ru

Что выбрать, если не их.

Определение и применение

CSS свойство flex-wrap определяет, будет ли флекс контейнер однострочным, или многострочным. По умолчанию контейнер является однострочным, для многострочных контейнеров допускается контролировать направление, в котором размещаются флекс элементы.

Обращаю Ваше внимание, если элемент не является флекс элементом (не находится внутри родительского элемента, который является блочным, или строчным флекс контейнером), то свойство flex-wrap не окажет на такой элемент никакого эффекта. Схематичное отображение работы свойства flex-wrap отображено на следующем изображении:

Схематичное отображение работы свойства flex-wrap отображено на следующем изображении:

Строки кода в блоке

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

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

Также я нарвалась на проблемы с адаптивностью при оформлении кода для github (gist), который особенно коварен из-за того, что это table. В таких случаях я понимаю, что мне придётся применить особенное оформление для переопределения контейнера таблицы.

A simple yet powerful tool

I have learned over the years that a business process and strategy can have powerful outcomes if it can be explained in a simple way. But ‘simple’ does not mean ‘easy’. It is often construed that way. Simplicity only makes understanding the problem easily. But arriving at the solution to the problem could still be hard. White space Analysis helps you to discover areas where you can grow your account, align and map your resources. This can help you identify your farming and mining white space opportunities. The analysis report provided can reveal some insight into what can be improved in the near future to increase sales and ROI.

One of the ways to simplicity is to identify the two variables/parameters and put them on a two-dimensional X & Y-axis. Then think of various possibilities at a different position of this grid. I set out to build software for Key Account Management. One of the basic, but the fundamental problem was to understand ‘Account Landscape’ and ‘Account Mapping’ to identify areas of growth in a Key Account.

As usual, I started thinking of two variables – people on both sides. this means the products & services of both parties again, opportunities, strategic initiatives of the customer and of my company, global footprint of the account. Finally, I arrived at ‘Buying Centres’ of the buyer Account & ‘Offerings’ of the seller as two variables to build the Account Landscape. The resulting matrix is a simple and yet powerful tool to understand the Key Account.

Deciding what offerings (products/services/solutions) to take to market is not easy?  That is the most fundamental aspect of any business. That’s for the management to decide. But an Account Manager has to identify the ‘buying centers’. These are the units in that account where one can take my offerings independently. These are usually divisions/functions and for a global account combined with regions. For example: ‘Retail Banking Europe’ & ‘Merchant Banking’ could be buying centers for a Bank.

This will set the Account Manager thinking, which offering is applicable to which buying center(s). Which of those boxes are easier to penetrate? Maybe because my offering there has a compelling value proposition for that buying center and there seems to be no incumbent competitor either. That is my ‘White space’ of growth.
The following Account Landscape shows the progress in that account over the years.

Свойство word-wrap

В HTML для разделения строк существует специальный тег <br>. Но его слишком частое использование считается среди разработчиков дурным тоном и зачастую свидетельствует о непрофессионализме. Как доказательство, представьте, что у вас есть логотип и вы хотите, чтобы каждая буква начиналась с новой строки:

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

Первое свойство, к которому стоит обратиться для обработки текста, — это word-wrap. Принимает три значения: normal, break-all и keep-all. Вам для работы понадобится запомнить только break-all. Normal стоит по умолчанию, и его нет смысла указывать. Keep-all означает в документе CSS запрет переноса строки. Разработано специально для китайских, японских и корейских иероглифов. Поэтому, если вы не собираетесь вести блог на каком-то из этих языков, свойство вам не пригодится. А также оно не поддерживается браузером Safari и мобильными телефонами на базе iOS.

Чтобы логотипу из предыдущего примера назначить с помощью CSS перенос на новую строку каждой буквы, нужно прописать следующий код:

Ширина и размер шрифта подбирается таким образом, чтобы места хватало только для одной буквы. Word-wrap со значением break-all сообщает браузеру, что слово нужно каждый раз переносить на новую строку. Незаменимым это свойство назвать нельзя. Но оно пригодится при оформлении небольших блоков с текстом, например полей для ввода комментариев.

Бонус — br clear

А как сделать так чтобы текст, в котором вы поставили перенос строки, не обтекал плавающий элемент (это либо изображение с установленным align, либо элемент со свойством float), а начинался ниже элемента? Для этого можно использовать атрибут clear.

Допустим, у нас есть изображение выровненное по левому краю (align=»left»). Если мы установим <br clear=»all»> или <br clear=»left»>, то текст после тега <br> (следующая строка, которую мы и переносим) будет отображаться как надо, ниже рисунка. Другие значения атрибута clear тега <br> сделают так, чтобы текст обтекал рисунок, расположившись справа от него.

Использование этого специфичного атрибута не приветствуется спецификацией HTML — такой код будет невалидным.

Кстати, рекомендуем прочесть: Как вставить изображение в HTML.

Свойства

В конце концов при решении проблем с переносом текста остается некий типичный «список подозреваемых». Одни довольно очевидные и логичные, а другие — нет. Одни делают свое дело сами по себе, а другие не очень.

Итак, давайте взглянем.

Свойство принимает в виде значений два ключевых слова: (по умолчанию) и . Это в дополнение к трём глобальным значениям , и .

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

В первом примере этого демо можно наглядно увидеть поведение по умолчанию:

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

Важно заметить: было заменено на , но значения остались прежними. И взгляните

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

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

hyphens

Свойство hyphens рассказывает браузеру, как расставлять дефис при переносе, и допускает следующие значения: , и , которые в настоящий момент , поэтому вам, видимо, придётся запустить FireFox.

Значение гарантирует, что в слова никогда не будет подставляться символ переноса.

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

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

Мягкий перенос () делает тоже самое, но фактически не отображает дефис на экране, что, как правило, предпочтительнее.

При значении слова можно разбивать либо в явно указанных местах, либо автоматически, в соответствии с правилами расстановки переносов для конкретного языка, указанными в специальных файлах (если они предусмотрены в браузере). Расстановка переносов специфична для языка, и для документа нужно определять атрибут .

white-space

У каждого из нас есть любимые CSS-свойства, на которые можно положиться, словно на запасной выход с надписью «При аварии разбить стекло молотком», чтобы выбраться из запутанной ситуации; см. также и . Для меня таким свойством является .

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

У этого свойства бывает пять значений: (по умолчанию), , , и .

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

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

(пример 2) также игнорирует дополнительные пробелы, но зато не разбивает строку текста на границах контейнера.

учитывает все пробельные символы в разметке, и не разбивает строки (как видно выше в примере 3).

(пример 4) учитывает добавочные пробелы, но заставляет строку разбиваться.

(последний пятый пример) схлопывает пробельные символы (кроме перевода строки) и принуждает «цепочку» текста умещаться в контейнер.

На CSS—Tricks есть удобная табличка, которая поможет всё это резюмировать.

Слишком длинные ссылки

Я постоянно сталкивалась с проблемой слишком длинных ссылок, снова, при подготовке электронной книги (да, при публикации электронной книги это буквально худшее) с множеством целых ссылок в сносках.

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

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

Управление регистром букв: text-transform

Иногда возникает необходимость вывести слова или первые символы слов с заглавной буквы. В CSS для управления регистром буквы есть свойство .

Дефолтное значение равно , то есть по умолчанию регистр букв не изменяется.

Значение

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

Разметка:

Стили:

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

Значение

Если ваша цель — сделать все буквы заглавными, то подходящим значением будет :

Разметка:

Стили:

Значение

Это значение наоборот делает все символы строчными. Естественно, оно не оказывает никакого воздействия на уже имеющиеся строчные буквы.

Разметка:

Стили:

Значение

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

Не у всех символов есть соответствующая форма, и, значит, не на все символы будет влиять это значение:

Разметка:

Стили:

Это свойство на данный момент поддерживается только в Firefox.

Дополнительная информация

Браузеры отлично поддерживают свойство , у всех основных браузеров с ним нет проблем.

Единственное исключение это значение , которое работает пока только в Firefox. И такая непопулярность вполне может повлечь исключение этого значения из спецификаций.

Также есть небольшое отличие в обработке у Firefox и остальных браузеров.

Вот, например, Firefox:

Заметьте, что первая буква после дефиса не капитализируется. А вот тот же самый пример в Chrome:

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

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

Firefox DevTools to the rescue!

Starting with version 52 of Firefox, the inspector panel shows white space text nodes when they do have an impact on the layout and also highlights them in the page.

How does the inspector know when a node impacts the layout? It simply checks if that white space text node has a size. When a text node is ignored, it’ll have a width and height of 0, but when it participate in the layout, it’ll have some dimension.So, using this simple heuristic, Firefox DevTools can show the white space text nodes that are important.

White space text nodes displayed in the inspector and highlighted in the page. See live at https://captainbrosset.github.io/white-space-article/example4.html.

As you can see above, the white space text nodes that do have a size in the page are now shown in the inspector panel and, if you hover over them, they are also highlighted in the page so you know exactly where they are and how big they are.

This way, if you were originally confused about why the avatars in the page didn’t sit next to each other, it will now be very obvious why that is. No more loosing time looking for margins that aren’t there or crafting the right google search query that will give you the answer.

In fact, you can even remove these text nodes and see that the inline-block elements are now displayed exactly as you wanted them to.

Deleting white space text nodes. See live at https://captainbrosset.github.io/white-space-article/example4.html.

Firefox 52 is now available as a Nightly build, so go ahead and grab it and take it for a spin.

Hopefully this new feature and this article have been helpful, thanks for reading!

white-space | htmlbook.ru

Internet Explorer Chrome Opera Safari Firefox Android iOS
6.0+ 8.0+ 1.0+ 4.0+ 9.5+ 1.0+ 3.0+ 1.0+

3.5+

1.0+ 1.0+

Описание

Свойство white-space устанавливает, как отображать
пробелы между словами. В обычных условиях любое количество пробелов в коде HTML
показывается на веб-странице как один. Исключением является тег <pre>,
помещенный в этот контейнер текст выводится со всеми пробелами, как он был отформатирован
пользователем. Таким образом, white-space имитирует
работу тега <pre>, но в отличие от него не меняет шрифт
на моноширинный.

Значения

normal
Текст в окне браузера выводится как обычно, переносы строк устанавливаются
автоматически.

nowrap
Пробелы не учитываются, переносы строк в коде HTML игнорируются, весь текст отображается одной строкой;
вместе с тем, добавление тега <br> переносит текст
на новую строку.
pre
Текст показывается с учетом всех пробелов и переносов, как они были добавлены
разработчиком в коде HTML.
Если строка получается слишком длинной и не помещается в окне браузера, то будет добавлена горизонтальная полоса прокрутки.
pre-line
В тексте пробелы не учитываются, текст автоматически переносится на следующую строку, если он не помещается в заданную область.
pre-wrap
В тексте сохраняются все пробелы и переносы, однако если строка по ширине не помещается в заданную область, то текст автоматически будет перенесен на следующую строку.
inherit
Наследует значение родителя.

Действие значений на текст представлено в табл. 1.

Табл. 1. Перенос текста и пробелы при разных значениях white-space
Значение Перенос текста Пробелы
normal Переносится Не учитываются
nowrap Не переносится Не учитываются
pre Не переносится Учитываются
pre-line Переносится Не учитываются
pre-wrap Переносится Учитываются

Пример

HTML5CSS2.1IECrOpSaFx

Результат данного примера показан на рис. 1.

Рис. 1. Применение свойства white-space

Браузеры

Браузер Internet Explorer до версии 7.0 включительно не поддерживает значения pre-line, pre-wrap и inherit. Для <textarea> значения normal и pre ведут себя как pre-wrap, а значение nowrap ведет себя как pre-line.

Opera до версии 9.5 не поддерживает значение pre-line. Для <textarea> значения normal и pre ведут себя как pre-wrap, а значение nowrap ведет себя как pre-line.

Safari до версии 3.0 и iOS не поддерживают значения pre-wrap и pre-line.

Firefox до версии 2.0 включительно не поддерживает значения pre-line и pre-wrap. Для <textarea> значения normal, nowrap, и pre воспринимаются как pre-wrap.

Spaces between inline and inline-block elements

In fact, we’ve seen this already with the very first example in this article, when we described how white space was processed inside inline formatting contexts.

We said that there were rules to ignore most characters but that certain spaces staid in order to, basically, separate words.

So, when you’re actually dealing with text only, paragraphs that may contain inline elements such as em, strong, span, etc. you don’t normally care about this because the extra white spaces that do make it to the layout are actually helpful to separate the words.

But it gets more interesting when you start using inline-block elements. These elements appear as inline elements from the outside, but behave like blocks on the inside, so they are very often used to display more complex pieces of UI than just text side by side on the same line (just like if you floated blocks).

I think the expectation from web developers is that because they are blocks, they will behave as such, and just stack side by side (rather than on top of each other), but really they don’t. If there is formatting white space in the markup between them, then that will create space in the layout just like between text.

Consider this example:

<style>  .people-list { list-style-type: none; margin: 0; padding: 0; }  .people-list li { display: inline-block; width: 2em; height: 2em; background: #f06; border: 1px solid; }</style><ul class="people-list">⏎◦◦<li></li>⏎◦◦<li></li>⏎◦◦<li></li>⏎◦◦<li></li>⏎◦◦<li></li>⏎</ul>

If you open this in a browser, you’ll see the following result:

See live at https://captainbrosset.github.io/white-space-article/example4.html.

Which is most probably not what you intended. Let’s assume this is a list of people’s avatars and you wanted them displayed like this instead:

Well, this is a very common CSS layout problem and questions and articles have been written about this. There exist solutions, things like getting rid of the white space altogether, setting your font-size to 0, or using negative margin, etc.

What is interesting here isn’t really the solution to this common problem, but the fact that this is a common problem at all, and that many web developers have spent at least a little bit of time confronted to.Suddenly white space does show up in your layout in a way you didn’t expect and it may take you a while to figure out the problem.

Because the corresponding text nodes aren’t in devtools, people loose time on this common problem if they haven’t faced it before. They’ll check if there is margin somewhere but won’t find any.

So that’s one example of when showing white space text nodes in devtools would actually be useful. Let’s see another one.

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

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

Adblock
detector