Все способы вертикального выравнивания в css

Горизонтальное меню по центру без выпадающих пунктов

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


Разберем все по порядку, здесь все просто.  Мы создаем контейнер «mainmenu», куда помещаем наше меню в виде неупорядоченного списка.

Теперь дело идет за стилями css. Сначала мы сбрасываем на ноль все поля и отступы для всех браузеров. Далее при помощи свойства «float:left» мы смещаем наш неупорядоченный список влево и далее относительным позиционированием смещаем его на 50% вправо. Ширина списка «ul» будет равна сумме длин всех пунктов «li», которые находятся внутри него. Таким образом, если мы мысленно поделим окно браузера пополам, то наше меню уйдет вправо от линии разделения. Чтобы выровнять мы применим к пунктам «li» также относительное позиционирование и сместим их влево на 50%, указав свойство «left:-50%». Да и еще, чуть не забыл, нашему контейнеру «mainmenu» нужно обязательно указать свойство «overflow:hidden», иначе мы получим горизонтальную полосу прокрутки.

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

Горизонтальное меню по центру с выпадающими пунктами


Теперь разберем многоуровневое меню с выпадающими подпунктами. Здесь ситуация несколько иначе и несколько сложнее, т.к. в первом случае у нас подпункты выпадать не  будут, потому что мы указали блоку «mainmenu» свойство — «overflow:hidden». Это говорит, что элементы за пределами данного блока показываться не будут. Но выход есть.

Итак, я изменил предыдущий код и удалил из него свойство «overflow:hidden».

Definition and Usage

The property specifies how to align the last line of a text.

Notice that the property sets the alignment for all last lines within the selected element. So, if you have a <div> with three paragraphs in it, will apply to the last line of EACH of the paragraphs. To use on only the last paragraph in the container, you can use :last child, see example below.

Note: In Edge/Internet Explorer the property only works on text that has «text-align: justify».

Default value: auto
Inherited: yes
Animatable: no. Read about animatable
Version: CSS3
JavaScript syntax: object.style.textAlignLast=»right» Try it

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS 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

Centering vertically in CSS level 3

CSS level 3 offers other possibilities. At this time (2014), a good way to center blocks vertically without using absolute positioning (which may cause overlapping text) is still under discussion. But if you know that overlapping text will not be a problem in your document, you can use the ‘transform’ property to center an absolutely positioned element. For example:

This paragraph is vertically centered.

For a document that looks like this:

<div class=container3>
  <p>This paragraph…
</div>

the style sheet looks like this:

div.container3 {
   height: 10em;
   position: relative }              /* 1 */
div.container3 p {
   margin: 0;
   position: absolute;               /* 2 */
   top: 50%;                         /* 3 */
   transform: translate(0, -50%) }   /* 4 */

The essential rules are:

  1. Make the container relatively positioned, which declares it to be a container for absolutely positioned elements.

  2. Make the element itself absolutely positioned.

  3. Place it halfway down the container with ‘top: 50%’. (Note that 50%’ here means 50% of the height of the container.)

  4. Use a translation to move the element up by half its own height. (The ‘50%’ in ‘translate(0, -50%)’ refers to the height of the element itself.)

Recently (since about 2015), another technique has also become available in several CSS implementations. It is based on the new ‘flex’ keyword for the ‘display’ property. This keyword is meant for use in graphical user interfaces (GUIs), but nothing stops you from using it in a document, if the document happens to have the right structure.

This paragraph is vertically centered.

the style sheet looks like this:

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

Centering vertically

CSS level 2 doesn’t have a property for centering things vertically. There will probably be one in CSS level 3 (see ). But even in CSS2 you can center blocks vertically, by combining a few properties. The trick is to specify that the outer block is to be formatted as a table cell, because the contents of a table cell can be centered vertically.

The example below centers a paragraph inside a block that has a certain given height. A separate example shows a paragraph that is centered vertically in the browser window, because it is inside a block that is absolutely positioned and as tall as the window.

DIV.container {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle }
...
<DIV class="container">
  <P>This small paragraph...
</DIV>

Property Values

Value Description Play it
stretch Default value. Lines stretch to take up the remaining space Play it »
center Lines are packed toward the center of the flex container Play it »
flex-start Lines are packed toward the start of the flex container Play it »
flex-end Lines are packed toward the end of the flex container Play it »
space-between Lines are evenly distributed in the flex container Play it »
space-around Lines are evenly distributed in the flex container, with half-size spaces on either end 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

С этим читают