Css свойство text-overflow

Значения

visible
Содержимое не обрезается, когда выходит за пределы своего контейнера. Это значение по умолчанию.
hidden
Выходящий за границы контейнера контент будет скрыт.
scroll
Аналогично hidden, за исключением того, что добавляется полоса прокрутки, чтобы пользователи могли прокручивать скрытый контент.
auto
Если контент выходит за пределы своего контейнера, этот контент будет скрыт и появится полоса прокрутки. То есть в отличие от предыдущего значения полоса прокрутки появится только при необходимости.
initial
использует значение по умолчанию – .
inherit
перенимает значение переполнения от родительского элемента.

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

Possible Values

The property is shorthand, and accepts one or two keywords (below). If it has one keyword, that keyword sets both and ; if it has two keywords, it sets to the first and to the second

Specifies that the content should not be clipped. In other words, it should be displayed outside the content box.
Specifies that the content is clipped (i.e. the parts that extend beyond the content box are hidden), and no scroll bars (or other scrolling mechanism) are supplied.
Specifies that the content box should provide scroll bars (or other scrolling mechanism) regardless of whether the content is clipped or not.
Specifies that the content box should provide scroll bars (or other scrolling mechanism) only when the content overflows (i.e. is too big to fit within the content box).

In addition, all CSS properties also accept the following CSS-wide keyword values as the sole component of their property value:

Represents the value specified as the property’s initial value.
Represents the computed value of the property on the element’s parent.
This value acts as either or , depending on whether the property is inherited or not. In other words, it sets all properties to their parent value if they are inheritable or to their initial value if not inheritable.

CSS Свойства

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-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-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-eventspositionquotesresizerighttab-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

Hidden

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

See the Pen
overflow hidden by Андрей (@adlibi)
on CodePen.

Текст, который выходит за пределы , перестал быть видимым.

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

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

gap
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
row-gap

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

Possible Keywords For Overflow

The property can accept the following possible values:

Since is a short hand property, it can accept one or two values. The first value is for the horizontal axis, and the second one is for the vertical axis.

Visible

The default value, where the content can extend beyond its parent. It can be set like:

An interesting fact that you should know is that when one axis is set to , and another axis is set to , the axis with will compute to the keyword.

According to Mozilla Developer Network MDN:

For example, if we set an element with the following:

The property computed value will be .

Hidden

When content is longer than its parent, it will be clipped. However, the content can be scrolled by using Javascript.

The scroll value Allows scrolling to reveal the clipped content, and it can be horizontal or vertical.

In the figure above, the scrollbar is always visible regardless if the content is long or not. Note that this depends on the operating system.

Auto

I consider this a smart keyword! It shows the scrollbar only if the content is longer than its container.

Notice that in the figure, the scrollbar is only visible in case the content is longer than its container. Next, we will go through the longhand properties that are related to .

Пример использования

<!DOCTYPE html>
<html>
<head>
<title>Пример использования свойств overflow-x и overflow-y.</title>
<style> 
div {
display  : inline-block; /* выравниваем вертикально все элементы <div> */
margin-right : 30px; /* устанавливаем внешний отступ справа для элементов <div> */
width : 100px; /* устанавливаем ширину для блоков */
height : 100px; /* устанавливаем высоту для блоков */
border : 1px solid red; /* устанавливаем для блоков сплошную границу размером 1px красного цвета*/
}
img {
width : 125px; /* устанавливаем ширину для изображения */
height : 125px; /* устанавливаем высоту для изображения */
}
.test {
overflow-x : visible; /* переполнение левого, либо правого края элемента не обрезается, содержимое выходит за пределы размеров элемента */
overflow-y : visible; /* переполнение верхнего, либо нижнего края элемента не обрезается, содержимое выходит за пределы размеров элемента */
}
.test2 {
overflow-x : hidden; /* переполнение левого, либо правого края элемента обрезается (контент, который выходит за размеры будет невидимым) */
overflow-y : hidden; /* переполнение верхнего, либо нижнего края элемента обрезается (контент, который выходит за размеры будет невидимым) */
}
.test3 {
overflow-x : scroll; /*  переполнение левого, либо правого края элемента обрезается, но добавляется полоса прокрутки */
overflow-y : scroll; /*  переполнение верхнего, либо нижнего края элемента обрезается, но добавляется полоса прокрутки */
}
.test4 {
overflow-x : auto; /* если переполнение левого, либо правого края элемента будет обрезано, то добавится полоса прокрутки автоматически */
overflow-y : auto; /* если переполнение верхнего, либо нижнего края элемента будет обрезано, то добавится полоса прокрутки автоматически */
}
</style>
</head>
	<body>
		<div class = "test">visible
			<img src = nich.jpg alt = ничоси>
		</div>
		<div class = "test2">hidden
			<img src = nich.jpg alt = ничоси>
		</div>
		<div class = "test3">scroll
			<img src = nich.jpg alt = ничоси>
		</div>
		<div class = "test4">auto
			<img src = nich.jpg alt = ничоси>
		</div>
	</body>
</html>

Пример использования свойств overflow-x и overflow-y (переполнение элементов содержимым).CSS свойства

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex
Responsive

Visible

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

На примере ниже выводится , в котором находится текст. У этого div указана высота и сделана синяя рамка, чтобы были видны границы. И хорошо видно, что хотя сам блок заканчивается нижней рамкой, текст идет ниже и выходит за его пределы. Все потому, что по умолчанию видимость при переполнении установлена в – видима.

See the Pen
overflow visible by Андрей (@adlibi)
on CodePen.

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

See the Pen
overflow flow by Андрей (@adlibi)
on CodePen.

Говоря в целом: не стоит без особой причины устанавливать фиксированную высоту элементов.

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-weightgapgridgrid-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-eventspositionquotesresizerightrow-gapscroll-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 свойство text-overflow указывает, что должно произойти, когда текст переполняет, содержащий элемент.

Применение свойства рассматривается в тех ситуациях, когда текст обрезается, либо когда он переполняет содержимое элемента, в этих случаях текст можно обрезать, поставить троеточие (‘…’, Юникод — U+2026), или отобразить определенную пользовательскую строку(в настоящее время поддерживается только в Firefox).
Т.е. text-overflow происходит, когда свойство overflow имеет значения hidden, scroll или auto и свойство white-space имеет значение nowrap (перенос слов запрещён).

Свойство text-overflow применяется только к блочным, либо блочно-строчным элементам, поскольку элемент должен иметь заданную ширину, кроме того переполнение происходит в зависимости от направления текста заданного свойством direction, либо глобальным HTML атрибутом dir.

overflow-x and overflow-y

The and properties specifies
whether to change the overflow of content just horizontally or vertically (or
both):

specifies what to do with the left/right edges of the
content. specifies what to do with the top/bottom edges of the
content.

You can use the overflow property when you want to have better control of the layout. The overflow property specifies what happens if content overflows an element’s box.

Example

div {  overflow-x: hidden; /* Hide horizontal scrollbar
*/  overflow-y: scroll; /* Add vertical scrollbar */}

All CSS Overflow Properties

Property Description
overflow Specifies what happens if content overflows an element’s box
overflow-x Specifies what to do with the left/right edges of the content if it overflows the element’s content area
overflow-y Specifies what to do with the top/bottom edges of the content if it overflows the element’s content area

❮ Previous
Next ❯

Очистка Float

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

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

На примере это наглядно видно. Внутри родительского элемента (в синей рамке) помещен элемент с текстом и установленным свойством . Родительский элемент при этом свернулся.

See the Pen
overflow float by Андрей (@adlibi)
on CodePen.

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

See the Pen
overflow float 2 by Андрей (@adlibi)
on CodePen.

Vendor Prefixes

For maximum browser compatibility many web developers add browser-specific properties by using extensions such as for Safari, Google Chrome, and Opera (newer versions), for Internet Explorer, for Firefox, for older versions of Opera etc. As with any CSS property, if a browser doesn’t support a proprietary extension, it will simply ignore it.

This practice is not recommended by the W3C, however in many cases, the only way you can test a property is to include the CSS extension that is compatible with your browser.

The major browser manufacturers generally strive to adhere to the W3C specifications, and when they support a non-prefixed property, they typically remove the prefixed version. Also, W3C advises vendors to remove their prefixes for properties that reach Candidate Recommendation status.

Many developers use Autoprefixer, which is a postprocessor for CSS. Autoprefixer automatically adds vendor prefixes to your CSS so that you don’t need to. It also removes old, unnecessary prefixes from your CSS.

You can also use Autoprefixer with preprocessors such as Less and Sass.

Значения свойства

Значение Описание
visible Переполнение не обрезается, содержимое выходит за пределы размеров элемента. Это значение по умолчанию.
hidden Переполнение обрезается (контент, который выходит за размеры будет невидимым).
scroll Переполнение обрезается, но добавляется полоса прокрутки, позволяющая увидеть содержимое, которое выходит из заданных размеров.
auto Если переполнение обрезается, то полоса прокрутки будет добавлена автоматически, чтобы увидеть содержимое, которое выходит из заданных размеров.
initial Устанавливает свойство в значение по умолчанию.
inherit Указывает, что значение наследуется от родительского элемента.

Example Code

Working Example within an HTML Document

<!doctype html>
<title>Example</title>
<style>
.clipped {
width: 150px;
height: 110px;
padding: 20px;
background-color: gold;
border: 5px solid orange;
overflow: scroll;
}
</style>

<div class=»clipped»>
<p>Change the value to see the difference between <code>visible</code>, <code>scroll</code>, <code>auto</code>, and <code>hidden</code>. Browser support for <code>no-display</code> and <code>no-content</code> is limited or non-existent at the time of writing, so they may not work as expected.</p>
<p>Oh, and don’t forget to visit Taumatawhakatangihangakoauauotamateapokaiwhenuakitanatahu!</p>
</div>

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

gap
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
row-gap

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

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

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

Adblock
detector