Свойство css text-align

Выравнивание текста по центру CSS

Как правило, совместно с задачей выровнять текст по вертикали необходимо сделать выравнивание текста по центру в CSS. Для этого мы можем использовать стандартное свойство text-align со значением center, которое нужно задать для родительского элемента, то есть для блока, в котором находится нужный текст.

Зададим для блока с текстом, который мы использовали в первом примере, выравнивание текста по ширине в CSS:

CSS

.text-vertical-al p{
display:table-cell;
vertical-align:middle;
text-align:center;
}

1
2
3
4
5

.text-vertical-al p{

displaytable-cell;

vertical-alignmiddle;

text-aligncenter;

}

Теперь текст выровнен точно по центру блока:

Выравнивание текста по вертикали CSS

Обратите внимание! Свойство text-align:center; задано для тега , так как в данном случае абзац является родительским блоком для текста.

Right-aligned text

Right-aligning text is straightforward with the environment .

\begin{flushright}
Hello, here is some text without a meaning.  This text should show what 
a printed text will look like at this place.  If you read this text, 
you will get no information.  Really?  Is there no information?  Is there 
a difference between this text and some nonsense like not at all!  A 
blind text like this gives you information about the selected font, how 
the letters are written and an impression of the look.  This text should
contain all letters of the alphabet and it should be written in of the
original language.There is no need for special content, but the length of
words should match the language.
\end{flushright}

This  is  the  second  paragraph. Hello, here is some text without 
a meaning.  This text should show what 
a printed text will look like at this place.  If you read this text, 
you will get no information.  Really?  Is there no information?  Is there 
a difference between this text and some nonsense like not at all!  A 
blind text like this gives you information about the selected font, how 
the letters are written and an impression of the look.  This text should
contain all letters of the alphabet and it should be written in of the
original language.There is no need for special content, but the length of
words should match the language.

Text in between and is right-justified. If you prefer the corresponding environment in that package is .

The switch command will also produce right-aligned text, but the behaviour is different; in this case the text will be right-aligned from the point where the command is declared till another switch command is used. This is more suitable for large blocks of text or for the whole document. The equivalent command in is .

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

CSS свойство align-content определяет как браузер распределяет пространство между и вокруг флекс элементов вдоль поперечной оси контейнера (вертикально), или производит выравнивание всего макета сетки по оси столбца grid-контейнера.

Для того, чтобы определить как браузер распределяет пространство между и вокруг флекс элементов вдоль главной оси контейнера (горизонтально), или производит выравнивание всего макета сетки по оси строки grid-контейнера, вы можете воспользоваться свойством justify-content.

При работе с флекс элементами обратите внимание на то, что свойство align-content возможно применить только к многострочным флекс контейнерам (flex-wrap, или flex-flow со значениями wrap | wrap-reverse). Если элемент не является флекс элементом, или элементом сетки макета (не находится внутри родительского элемента, который является блочным, или строчным флекс, или grid-контейнером), то свойство align-content не окажет на такой элемент никакого эффекта

Если элемент не является флекс элементом, или элементом сетки макета (не находится внутри родительского элемента, который является блочным, или строчным флекс, или grid-контейнером), то свойство align-content не окажет на такой элемент никакого эффекта.

Более подробную информацию о работе с флекс элементами вы можете получить в статье учебника CSS «Верстка по Flexbox (работа с контейнерами)».

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

* — для элементов сетки макета (grid-элементы) допускается использование сокращенных значений start и end, для флекс элементов необходимо использовать полные значения flex-start и flex-end.

Property Values

Value Description Play it
auto Default value. The last line is justified and aligned left Play it »
left The last line is aligned to the left Play it »
right The last line is aligned to the right Play it »
center The last line is center-aligned Play it »
justify The last line is justified as the rest of the lines Play it »
start The last line is aligned at the beginning of the line (left if the text-direction is left-to-right, and right is the text-direction is right-to-left) Play it »
end The last line is aligned at the end of the line (right if the text-direction is left-to-right, and left is the text-direction is right-to-left) 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 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

Fully justified text

In LaTeX text is fully-justified by default and if a switch command such as or is used the text alignment can not be switched back. For this case scenario you can use the package ragged2e. Import it adding to the preamble, then use the command as shown in the example below.

\centering
Hello, here is some text without a meaning.  This text should show what 
a printed text will look like at this place.  If you read this text, 
you will get no information.  Really?  Is there no information?  Is there 
a difference between this text and some nonsense like not at all!  A 
blind text like this gives you information about the selected font, how 
the letters are written and an impression of the look.  This text should
contain all letters of the alphabet and it should be written in of the
original language.There is no need for special content, but the length of
words should match the language.

\justify
This  is  the  second  paragraph. Hello, here is some text without 
a meaning.  This text should show what 
a printed text will look like at this place.  If you read this text, 
you will get no information.  Really?  Is there no information?  Is there 
a difference between this text and some nonsense like not at all!  A 
blind text like this gives you information about the selected font, how 
the letters are written and an impression of the look.  This text should
contain all letters of the alphabet and it should be written in of the
original language.There is no need for special content, but the length of
words should match the language.

The first paragraph in the previous example is centred by and then the alignment is switched back to fully-justified text with .

ragged2e also provides the environment to fully-justify small blocks of text in a document that is entirely left or right aligned.

Вертикальное выравнивание

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

Выравнивание свойством line-height

В том случае, когда в блоке только одна строка, можно добиться ее выравнивания по вертикали, применив свойство «line-height» и установив ему желаемую высоту. Для надежности стоит установить еще и «height», значение которого будет равно значению «line-height», потому что последние поддерживается не во всех браузерах.

Это фиолетовая строчка, высота которой равна высоте блока.

.example-wrapper4{
line-height: 100px;
color: #DC09C0;
background: #E5DAE1;
height: 100px;
text-align: center;
}

Так же возможно добиться выравнивания блока с несколькими строками. Для этого придется использовать дополнительный блок-обертку, и устанавливать высоту строки ему. Внутренний блок может быть многострочным, но обязательно «inline». К нему нужно применить «vertical-align: middle».

А это inline-элемент. Здесь несколько оранжевыхстрочек. Они выравниваятсяза счет установленной высоты строки блока-родителя.

.example-wrapper5 {
line-height: 160px;
height: 160px;
font-size: ;
background: #FF9B00;
}

.example-wrapper5 .text1{
display: inline-block;
font-size: 14px;
line-height: 1.5;
vertical-align: middle;
background: #FFFAF2;
color: #FF9B00;
text-align: center;
}

У блока обертки должно быть установлено «font-size: 0». Если не установить нулевой размер шрифта, то браузер добавит от себя несколько лишних пикселей. Также придется указать размер шрифта и высоту строки для внутреннего блока, ведь эти свойства наследуются от родителя.

Выравнивание по вертикали в таблицах

Свойство «vertical-align» также действует на ячейки таблицы. C установленным значением «middle», контент внутри ячейки выравнивается по центру. Конечно, табличная верстка в наше время считается архаической, но в исключительных случаях можно симулировать ее, указав «display: table-cell».

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

осталось 10 шт

307грн.($14.05)

осталось 7 шт

267грн.($16.79)

.one_product .img_wrapper {
display: table-cell;
height: 169px;
vertical-align: middle;
overflow: hidden;
background: #fff;
width: 255px;
}

.one_product img {
max-height: 169px;
max-width: 100%;
min-width: 140px;
display: block;
margin: 0 auto;
}

Следует помнить, что если у элемента установлено «float» отличное от «none», то он в любом случае будет блочным (display: block) — тогда придется использовать дополнительный блок-обертку.

Выравнивание дополнительным inline-элементом

И для inline-элементов можно применить «vertical-align: middle». При этом все элементы с «display: inline», которые находятся в одной строке, выровняются относительно общей центральной линии.

Нужно создать вспомогательный блок с высотой, равной высоте родительского блока, тогда и желаемый блок выровняется по центру. Для этого удобно использовать псевдоэлементы :before или :after.

.example-wrapper6{
height: 300px;
text-align: center;
background: #70DAF1;
}


.pudge {
display: inline-block;
vertical-align: middle;
background: url(pudge.png);
background-color: #fff;
width: 200px;
height: 200px;
}


.riki { 
display: inline-block;
height: 100%;
vertical-align: middle;
}

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

Значение Описание
baseline Выравнивает базовую линию текущего элемента по базовой линии родителя. Это значение по умолчанию.
length Поднимает или опускает базовую линию элемента на указанную величину относительно базовой линии родителя. Величина смещения указывается в единицах измерения, применяемых в CSS. При использовании положительного значения смещение происходит вверх, при отрицательном — вниз. Допускаются отрицательные значения
% Поднимает или опускает базовую линию элемента на указанную величину. Величина смещения в процентах расчитывается в зависимости от высоты строки (свойство line-height). При использовании положительного значения смещение происходит вверх, при отрицательном — вниз. Допускаются отрицательные значения
sub Выравнивает элемент, как подстрочный (нижний индекс).
super Выравнивает элемент, как надстрочный (верхний индекс).
top Верх элемента выравнивается по верху самого высокого элемента в строке.
text-top Верх элемента выравнивается с верхом шрифта родительского элемента.
middle Элемент размещается в середине родительского элемента.
bottom Низ элемента выравнивается с самым низким элементом в строке.
text-bottom Низ элемента выравнивается с низом шрифта родительского элемента.
initial Устанавливает свойство в значение по умолчанию.
inherit Указывает, что значение наследуется от родительского элемента.

Обращаю Ваше внимание, что при работе с ячейками таблицы применяются только следующие значения*:

Значение Описание
baseline Выравнивает базовую линию ячейки по базовой линии родителя. Это значение по умолчанию.
top Выравнивает содержимое ячейки вертикально по верхнему краю.
middle Выравнивает содержимое ячейки вертикально по середине.
bottom Выравнивает содержимое ячейки вертикально по нижнему краю.

* — Значения sub, super, text-top, text-bottom, length и %, примененные к ячейке таблицы будут вести себя как при использовании значения baseline.

HTML Text Align Center (Vertical | Horizontal)

You can set the HTML text-align middle on the webpage or Vertical center or horizontal center. Let’s see one by one example. (Note: Upper example is center the text for Vertical and Horizontal).

HTML Text align vertical center

Using Internal CSS and in <style> use 2 property- “display: table-cell;” and “vertical-align:middle;”

<html>
<head>
<style>
#test {
width: 200px;
height: 200px;
margin: 0;
background-color: gray;
color: white;
display: flex;
display: table-cell;
vertical-align:middle;
}
</style>
</head>

<body>
<h2>Tutorial</h2>
<div>

<p id=»test»>Center Vertical</p>
<div>
</div></div></body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<html>

<head>

<style>

#test {

width200px;

height200px;

margin;

background-colorgray;

colorwhite;

displayflex;

displaytable-cell;

vertical-alignmiddle;

}

</style>

<head>

<body>

<h2>Tutorial<h2>

<div>

<pid=»test»>Center Vertical<p>

<div>

<div><div><body>

<html>

Output:

Как использовать Flexbox

(О выборе между Grid и Flexbox можно почитать в статье «Grid — для макетов, Flexbox — для компонентов», — прим. ред. Techrocks).

Допустим, у нас есть документ, в котором по порядку идут три одинаковых элемента-потомка какого-нибудь родительского блока. Они располагаются друг за другом вертикально.

Но что, если нам нужно расположить их в ряд?

Здесь нам на помощь приходит Flexbox. Этот функционал CSS позволяет располагать элементы с учетом строк и столбцов, а также задавать промежутки между ними (пространство вокруг них).

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Position and Flexbox</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <div class="parent">
        <div class="child-one"></div>
        <div class="child-two"></div>
        <div class="child-three"></div>
    </div>
</body>
</html>

CSS:

/* Flexbox container */
.parent {
    background-color: #00AAFF;
    width: 300px;
    height: 300px;
    display: flex;
  }

  .child-one {
    background-color: rgb(116, 255, 116);
    width: 300px;
    height: 300px;
  }
  
  .child-two {
    background-color: rgb(248, 117, 117);
    width: 300px;
    height: 300px;
  }
  
  .child-three {
    background-color: rgb(255, 116, 232);
    width: 300px;
    height: 300px;
  }

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

Это расположение, принятое во Flexbox по умолчанию.

Давайте посмотрим другие варианты расположений.

Как располагать элементы при помощи Flexbox

flex-direction

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

Свойству назначают значение row, если элементы нужно расположить в ряд, слева направо (это значение по умолчанию):

Значение позволяет расположить элементы в виде столбцов, т. е. вертикально:

Значение работает так же, как , но порядок элементов будет обратным. Первый элемент станет последним, а последний — первым. расположение элементов будет противоположным тому, что было бы при значении :

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

justify-content

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

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

При значении — в начале страницы.

При значении — в конце страницы.

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

Вы видите, что пространства между , и одинаковые, а пространства перед и после — меньше.

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

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

align-items

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

Значение позволяет центрировать элементы по вертикали.

При значении элементы выравниваются по верхнему краю страницы.

При значении — выравниваются по нижнему краю.

Теперь вы знаете основы Flexbox.

Как выравнивать элементы по центру экрана

Свойства Flexbox можно использовать вместе. Например, если мы хотим расположить элементы по центру и по горизонтали, и по вертикали, мы можем задать и , и .

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

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

<!DOCTYPE html>
<html>
<head>
<title>Вертикальное позиционирование.</title>
<style> 
div {
width : 30%; /* задаём ширину блока */
}
img {
width : 75px; /* задаём ширину изображения */
height : 75px; /* задаём высоту изображения */
}
p {
background-color : orange; /* задаём задний фон для элемента <p> */
}
.top {
vertical-align : text-top; /* верх элемента выравнивается с верхом шрифта родительского элемента */
}
.bottom {
vertical-align : text-bottom; /* низ элемента выравнивается с низом шрифта родительского элемента */
}
</style>
</head>
	<body>
		<p>Baseline<img src = "nich.jpg" alt = "nich"></p>
		<p>Text-Top<img src = "nich.jpg" alt = "nich" class = "top"></p>
		<p>Text-Bottom<img src = "nich.jpg" alt = "nich" class = "bottom"></p>
	</body>
</html>

Пример вертикального позиционирования.CSS свойства

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

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

Adblock
detector