How to align text to the center, width, and edges of the page in HTML? Methods for vertical center alignment in CSS.

Very often in layout it is necessary to center some element horizontally and/or vertically. Therefore, I decided to make an article with different ways of centering, so that everything is at hand in one place.

Horizontal alignment margin: auto

Horizontal alignment using margin is used when the width of the centered element is known. Works for block elements:

Elem ( margin-left: auto; margin-right: auto; width: 50%; )

Specifying auto for the right and left margins makes them equal, which centers the element horizontally within the parent block.

text-align: center

This method is suitable for centering text within a block. text-align: center:

Alignment with text-align .wrapper ( text-align: center; )

I'm center aligned

position and negative margin left

Suitable for centering blocks of known width. We give the parent block position: relative to position relative to it, the centered element position: absolute , left: 50% and a negative margin-left whose value is equal to half the width of the element:

Alignment with position .wrapper ( position: relative; ) .wrapper p ( left: 50%; margin: 0 0 0 -100px; position: absolute; width: 200px; )

I'm center aligned

display: inline-block + text-align: center

The method is suitable for aligning blocks of unknown width, but requires a wrapper parent. For example, you can center a horizontal menu this way:

Alignment with display: inline-block + text-align: center; .navigation ( text-align: center; ) .navigation li ( display: inline-block; )

Vertical alignment line-height

To align one line of text, you can use the same height and line spacing values ​​for the parent block. Suitable for buttons, menu items, etc.

line-height .wrapper ( height: 100px; line-height: 100px; )

I'm vertically aligned

position and negative margin up

An element can be aligned vertically by giving it a fixed height and applying position: absolute and a negative margin up equal to half the height of the element being aligned. The parent block must be given position: relative:

Wrapper ( position: relative; ) elem ( height: 200px; margin: -100px 0 0; position: absolute; top: 50%; )

This way, using positioning and negative margins, you can center an element on the page.

display: table-cell

For vertical alignment, the display: table-cell property is applied to the element, which forces it to emulate a table cell. We also set its height and vertical-align: middle . Let's wrap all this in a container with the dislpay: table; property. :

Vertical alignment display: table-cell .wrapper ( display: table; width: 100%; ) .cell ( display: table-cell; height: 100px; vertical-align: middle; )

I'm vertically aligned

Dynamic alignment of an element on a page

We looked at ways to align elements on a page using CSS. Now let's take a look at the jQuery implementation.

Let's connect jQuery to the page:

I suggest writing a simple function to center an element on the page, let's call it alignCenter() . The element itself acts as an argument to the function:

Function alignCenter(elem) ( // code here )

In the body of the function, we dynamically calculate and assign the coordinates of the page center to the CSS left and top properties:

Function alignCenter(elem) ( elem.css(( left: ($(window).width() - elem.width()) / 2 + "px", top: ($(window).height() - elem. height()) / 2 + "px" // don't forget to add position: absolute to the element to trigger coordinates )) )

In the first line of the function, we get the width of the document and subtract from it the width of the element, divided in half - this will be the horizontal center of the page. The second line does the same thing, only with the height for vertical alignment.

The function is ready, all that remains is to attach it to the DOM readiness and window resize events:

$(function() ( // call the centering function when the DOM is ready alignCenter($(elem)); // call the function when resizing the window $(window).resize(function() ( alignCenter($(elem)); )) // element centering function function alignCenter(elem) ( elem.css(( // calculating left and top coordinates left: ($(window).width() - elem.width()) / 2 + "px", top: ($(window).height() - elem.height()) / 2 + "px" )) ) ))

Application of Flexbox

New CSS3 features, such as Flexbox, are gradually becoming commonplace. The technology helps create markup without using floats, positioning, etc. It can also be used to center elements. For example, apply Flexbox to the parent element.wrapper and center the content inside:

Wrapper ( display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; height: 500px; width: 500px; ) .wrapper .content ( margin: auto; /* margin: 0 auto; horizontal only */ /* margin: auto 0; vertical only */ ) Lorem ipsum dolor sit amet

This rule centers the element horizontally and vertically at the same time - margin now works not only for horizontal alignment, but also for vertical one. And without a known width/height.

Related resources Help the project
  • CSS
  • HTML
  • I think many of you who have had to deal with layout have encountered the need to align elements vertically and know the difficulties that arise when aligning an element to the center.

    Yes, there is a special multi-value vertical-align property in CSS for vertical alignment. However, in practice it doesn't work at all as expected. Let's try to figure this out.


    Let's compare the following approaches. Align using:

    • tables,
    • indentation,
    • line-height
    • stretching,
    • negative margin,
    • transform
    • pseudo element
    • flexbox.
    To illustrate, consider the following example.

    There are two div elements, with one of them nested within the other. Let's give them the corresponding classes - outer and inner.


    The challenge is to align the inner element with the center of the outer element.

    First, let's consider the case when the dimensions of the external and internal blocks are known. Let's add the rule display: inline-block to the inner element, and text-align: center and vertical-align: middle to the outer element.

    Remember that alignment only applies to elements that have an inline or inline-block display mode.

    Let's set the sizes of the blocks, as well as background colors so that we can see their borders.

    Outer ( width: 200px; height: 200px; text-align: center; vertical-align: middle; background-color: #ffc; ) .inner ( display: inline-block; width: 100px; height: 100px; background-color : #fcc; )
    After applying the styles, we will see that the inner block is aligned horizontally, but not vertically:
    http://jsfiddle.net/c1bgfffq/

    Why did it happen? The point is that the vertical-align property affects the alignment of the element itself, not its content (except when it is applied to table cells). Therefore, applying this property to the outer element did not produce anything. Moreover, applying this property to an inner element will also do nothing, since inline-blocks are aligned vertically relative to adjacent blocks, and in our case we have one inline block.

    There are several techniques to solve this problem. Below we will take a closer look at each of them.

    Alignment using a table The first solution that comes to mind is to replace the outer block with a table of one cell. In this case, the alignment will be applied to the contents of the cell, that is, to the inner block.


    http://jsfiddle.net/c1bgfffq/1/

    The obvious disadvantage of this solution is that, from a semantic point of view, it is incorrect to use tables for alignment. The second disadvantage is that creating a table requires adding another element around the outer block.

    The first minus can be partially removed by replacing the table and td tags with div and setting the table display mode in CSS.


    .outer-wrapper ( display: table; ) .outer ( display: table-cell; )
    However, the outer block will still remain a table with all the ensuing consequences.

    Alignment using indents If the heights of the inner and outer blocks are known, then alignment can be set using the vertical indents of the inner block using the formula: (H outer – H inner) / 2.

    Outer ( height: 200px; ) .inner ( height: 100px; margin: 50px 0; )
    http://jsfiddle.net/c1bgfffq/6/

    The disadvantage of the solution is that it is applicable only in a limited number of cases when the heights of both blocks are known.

    Aligning with line-height If you know that the inner block should occupy no more than one line of text, then you can use the line-height property and set it equal to the height of the outer block. Since the content of the inner block should not wrap to the second line, it is recommended to also add the white-space: nowrap and overflow: hidden rules.

    Outer ( height: 200px; line-height: 200px; ) .inner ( white-space: nowrap; overflow: hidden; )
    http://jsfiddle.net/c1bgfffq/12/

    This technique can also be used to align multiline text if you redefine the line-height value for the inner block, and also add the display: inline-block and vertical-align: middle rules.

    Outer ( height: 200px; line-height: 200px; ) .inner ( line-height: normal; display: inline-block; vertical-align: middle; )
    http://jsfiddle.net/c1bgfffq/15/

    The disadvantage of this method is that the height of the external block must be known.

    Alignment using “stretching” This method can be used when the height of the outer block is unknown, but the height of the inner one is known.

    To do this you need:

  • set relative positioning to the external block, and absolute positioning to the internal block;
  • add the rules top: 0 and bottom: 0 to the inner block, as a result of which it will stretch to the entire height of the outer block;
  • set the vertical padding of the inner block to auto.
  • .outer ( position: relative; ) .inner ( height: 100px; position: absolute; top: 0; bottom: 0; margin: auto 0; )
    http://jsfiddle.net/c1bgfffq/4/

    The idea behind this technique is that setting a height for a stretched and absolutely positioned block causes the browser to calculate the vertical padding in an equal ratio if it is set to auto .

    Alignment using negative margin-top This method has become widely known and is used very often. Like the previous one, it is used when the height of the outer block is unknown, but the height of the inner one is known.

    You need to set the external block to relative positioning, and the internal block to absolute positioning. Then you need to move the inner block down by half the height of the outer block top: 50% and raise it up by half its own height margin-top: -H inner / 2.

    Outer ( position: relative; ) .inner ( height: 100px; position: absolute; top: 50%; margin-top: -50px; )
    http://jsfiddle.net/c1bgfffq/13/

    The disadvantage of this method is that the height of the indoor unit must be known.

    Alignment using transform This method is similar to the previous one, but it can be used when the height of the inner block is unknown. In this case, instead of setting a negative pixel padding, you can use the transform property and move the inner block up using the translateY function and a value of -50% .

    Outer ( position: relative; ) .inner ( position: absolute; top: 50%; transform: translateY(-50%); )
    http://jsfiddle.net/c1bgfffq/9/

    Why was it impossible to set the value as a percentage in the previous method? Since percentage margin values ​​are calculated relative to the parent element, a value of 50% would be half the height of the outer box, and we would need to raise the inner box to half its own height. The transform property is perfect for this.

    The disadvantage of this method is that it cannot be used if the indoor unit has absolute positioning.

    Alignment with Flexbox The most modern way of vertical alignment is to use Flexible Box Layout (popularly known as Flexbox). This module allows you to flexibly control the positioning of elements on the page, arranging them almost anywhere. Center alignment for Flexbox is a very simple task.

    The outer block needs to be set to display: flex and the inner block to margin: auto . And it's all! Beautiful, is not it?

    Outer ( display: flex; width: 200px; height: 200px; ) .inner ( width: 100px; margin: auto; )
    http://jsfiddle.net/c1bgfffq/14/

    The disadvantage of this method is that Flexbox is supported only by modern browsers.

    Which method should I choose? You need to start from the problem statement:
    • To vertically align text, it is better to use vertical indents or the line-height property.
    • For absolutely positioned elements with a known height (for example, icons), the method with a negative margin-top property is ideal.
    • For more complex cases, when the height of the block is unknown, you need to use a pseudo element or the transform property.
    • Well, if you are so lucky that you do not need to support older versions of the IE browser, then, of course, it is better to use Flexbox.

    Vlad Merzhevich

    Due to the fact that the contents of table cells can be simultaneously aligned horizontally and vertically, the possibilities for controlling the position of elements relative to each other are expanded. Tables allow you to set the alignment of images, text, form fields, and other elements relative to each other and the web page as a whole. In general, alignment is mainly necessary to establish visual connections between different elements, as well as to group them together.

    Vertical centering

    One way to show the visitor the focus and name of the site is to use a splash page. This is the first page on which, as a rule, there is a flash splash screen or a picture expressing the main idea of ​​the site. The image is also a link to other sections of the site. You need to place this image in the center of the browser window, regardless of the monitor resolution. For this purpose, you can use a table with a width and height of 100% (example 1).

    Example 1: Centering the drawing

    Alignment TABLE ( width: 100%; /* Table width */ height: 100%; /* Table height */ )

    In this example, horizontal alignment is set using the align="center" tag parameter , and the contents of the cell may not be centered vertically, since this is the default position.

    To set the table height to 100%, you need to remove , the code will no longer be valid.

    Using the width and height to cover the entire available area of ​​the web page ensures that the content of the table will be aligned exactly in the center of the browser window, regardless of its size.

    Horizontal alignment

    By combining the align (horizontal alignment) and valign (vertical alignment) attributes of the tag , it is permissible to set several types of positions of elements relative to each other. In Fig. Figure 1 shows ways to align elements horizontally.

    Let's look at some examples of text alignment according to the figure below.

    Top Alignment

    To specify the top alignment of cell contents, for a tag you need to set the valign attribute with the value top (example 2).

    Example 2: Using valign

    Alignment

    Column 1 Column 2

    In this example, cell characteristics are controlled using tag parameters , but it’s also more convenient to change through styles. In particular, the alignment in cells is specified by the vertical-align and text-align properties (example 3).

    Example 3: Applying styles for alignment

    Alignment TABLE ( width: 100%; /* Table width */ ) #col1 ( width: 75%; /* First column width */ background: #f0f0f0; /* First column background color */ ) #col2 ( width: 25 %; /* Width of the second column */ background: #fc5; /* Background color of the second column */ text-align: right; /* Right alignment */ ) #col1, #col2 ( vertical-align: top; / * Top alignment */ padding: 5px; /* Margins around cell contents */ )

    Column 1 Column 2

    To shorten the code, this example uses grouping of selectors because the vertical-align and padding properties are applied to two cells at the same time.

    Bottom alignment is done in the same way, but instead of the top value, bottom is used.

    Center alignment

    By default, cell contents are aligned to the center of their vertical line, so if the columns have different heights, you need to set the alignment to the top edge. Sometimes you still need to leave the original alignment method, for example, when placing formulas, as shown in Fig. 2.

    In this case, the formula is located strictly in the center of the browser window, and its number is located on the right edge. To arrange the elements in this way, you will need a table with three cells. The outer cells should have the same dimensions, in the middle cell the alignment is centered, and in the right cell - along the right edge (example 4). This number of cells is required to ensure that the formula is positioned in the center.

    Example 4: Formula Alignment

    Alignment

    (18.6)

    In this example, the first cell of the table is left empty; it serves only to create an indent, which, by the way, can also be set using styles.

    Aligning Form Elements

    Using tables, it is convenient to determine the position of form fields, especially when they are interspersed with text. One of the design options for the form, which is intended for entering a comment, is shown in Fig. 3.

    To ensure that the text next to the form fields is right-aligned and the form elements themselves are left-aligned, you will need a table with an invisible border and two columns. The left column will contain the text itself, and the right column will contain text fields (example 5).

    Example 5: Aligning Form Fields

    Alignment

    Name
    Email
    A comment

    In this example, for those cells where right alignment is required, the align="right" attribute is added. To ensure that the Comment label is positioned at the top of multiline text, the corresponding cell is set to top-aligned using the valign attribute.

    In CSS, some seemingly simple things are not so easy to do. One of these things is alignment, i.e. when one element needs to be positioned in a certain way relative to another.

    This article presents some ready-made solutions that will help simplify the work of centering elements horizontally and/or vertically.

    Note: Below each solution is a list of browsers indicating the versions in which the specified CSS code works.

    CSS - Center Align Block

    1. Aligning one block to the center of another. In this case, the first and second blocks have dynamic sizes.

    ... ...

    Parent ( position: relative; ) .child ( position: absolute; left: 50%; top: 50%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50% , -50%); -ms-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); transform: translate(-50%, -50%) ; )

    • Chrome 4.0+
    • Firefox 3.6+
    • Internet Explorer 9+
    • Opera 10.5+
    • Safari 3.1+

    2. Aligning one block to the center of another. In this case, the second block has fixed dimensions.

    Parent ( position: relative; ) .child ( position: absolute; left: 50%; top: 50%; /* width and height of 2 blocks */ width: 500px; height: 250px; /* Values ​​are determined depending on its size */ /* margin-left = - width / 2 */ margin-left: -250px; /* margin-top = - height / 2 */ margin-top: -125px; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 4.0+
    • Opera 7.0+
    • Safari 1.0+

    3. Aligning one block to the center of another. In this case, the second block has dimensions specified in percentages.

    Parent ( position: relative; ) .child ( position: absolute; /* width and height of 2 blocks in % */ height: 50%; width: 50%; /* Values ​​are determined depending on its size in % */ left: 25%; /* (100% - width) / 2 */ top: 25%; /* (100% - height) / 2 */ )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 4.0+
    • Opera 7.0+
    • Safari 1.0+
    CSS - Horizontal Alignment

    1. Aligning one block element (display: block) relative to another (in which it is located) horizontally:

    ... ...

    Block ( margin-left: auto; margin-right: auto; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 6.0+
    • Opera 3.5+
    • Safari 1.0+

    2. Aligning a line (display: inline) or line-block (display: inline-block) element horizontally:

    ... ...

    Parent ( text-align: center; ) .child ( display: inline-block; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 3.0+
    • Internet Explorer 8.0+
    • Opera 7.0+
    • Safari 1.0+
    CSS - Vertical Alignment

    1. Center one element (display: inline, display: inline-block) relative to the other (in which it is located) in the center. The parent block in this example has a fixed height, which is set using the CSS line-height property.

    ... ...

    Parent ( line-height: 500px; ) .child ( display: inline-block; vertical-align: middle; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 3.0+
    • Internet Explorer 8.0+
    • Opera 7.0+
    • Safari 1.0+

    2. Centering one block relative to another vertically by representing the parent as a table, and the child as a cell of this table.

    Parent ( display: table; ) .child ( display: table-cell; vertical-align: middle; )

    Browsers that support this solution:

    • Chrome 1.0+
    • Firefox 1.0+
    • Internet Explorer 8.0+
    • Opera 7.5+
    • Safari 1.0+

    If you know any other interesting tricks or useful ready-made alignment solutions, then share them in the comments.

    Web designers use DIVs in their work every day. Without any understatement, this is the most popular tag. Open the source of any website and you will see that most, if not two thirds of the objects are enclosed in . Even with the advent of HTML5 and the emergence of serious competitors in the form of article or header, it continues to be inserted into markup everywhere. Therefore, I suggest you understand the issue of formatting and centering div blocks.

    What is DIV

    The name of the element comes from the English word division, which means division. When writing markup, it is used to break elements into blocks. DIVs enclose groups of content on a web page. For example, images, paragraphs with text. The tag does not affect the display of content in any way and does not carry any semantic load.

    DIV supports all global attributes. But for web design you only need two - class and id. You will only remember about everyone else in exotic cases, and that’s not a fact. The align attribute, which was previously used to center or left align divs, has been deprecated.

    When to use DIVs

    Imagine that the site is a refrigerator, and the DIVs are plastic containers into which you need to sort the contents. You wouldn't put fruit in the same container with liverwurst. You will place each type of product separately. Web content is generated in a similar way.

    Open any website and divide it into meaningful blocks. Header at the top, footer at the bottom, main text in the center. On the side there is usually a smaller column with advertising content or a tag cloud.

    Document

    Now look at each section in more detail. Start with header. The site header has a separate logo, navigation, first-level heading, and sometimes a slogan. Assign each semantic block its own container. This will not only separate the elements in the flow, but also make them easier to format. You'll find it much easier to center an object in a DIV tag by giving it a class or ID.

    Centering DIVs Using Margins

    When rendering web elements, the browser considers three properties: padding, marging and border. Padding is the space between content and its border. Margin - fields that separate one object from another. Border is the lines along the blocks. They can be assigned to all of them at once or only to one side:

    div( border: 1px solid #333; border-left: none; )

    These properties add space between objects and help you align and place them properly. For example, if a block with an image needs to be offset from the left edge to the center by 20%, you assign a margin-left value of 20% to the element:

    Block-with-img( margin-left: 20%; )

    Elements can also be formatted using their width values ​​and negative padding. For example, there is a block with dimensions 200px by 200px. First, let's assign it an absolute position and move it to the center by 50%.

    Div( position: absolute; left: 50%; )

    Now, to ensure that the centered DIV is positioned perfectly, we give it a negative margin to the left equal to 50% of its width, that is -100 pixels:

    Margin-left: -100px;

    In CSS this is called "air removal". But it has a significant drawback in the need to make constant calculations, which is quite difficult to do for elements with several levels of nesting. If the padding and border-width values ​​are specified, the browser will by default calculate the dimensions of the container as the sum of the thickness of the borders, the padding on the right and left, and the content itself inside, which can also come as a surprise.

    So when you need to center a DIV, use the box-sizing property with the value border-box. This will prevent the browser from adding padding and border values ​​to the overall width of the DIV element. To raise or lower an element, also use negative values. But in this case, they can be assigned to either the top or bottom field of the container.

    How to center a DIV block using automatic margins

    This is an easy way to center large blocks. You simply assign the width of the container and the margin property to auto. The browser will place a block in the middle with equal margins on the left and right, doing all the work itself. As a result, you do not risk getting confused in mathematical calculations and significantly save your time.

    Use the auto-field method when developing responsive apps. The main thing is to assign a width value to the container in em or percentage. The code in the example above will center the DIV and on any device, including mobile phones, it will occupy 90% of the screen.

    Alignment via display property: inline-block

    By default, DIV elements are considered block elements, and their display value is block. For this method you will need to override this property. Only suitable for DIVs with a parent container:

    Any text

    An element with the outer-div class is assigned a text-align property with a value of center, which centers the text inside. But for now the browser sees the nested DIV as a block object. For the text-align property to work, the inner-div must be treated as lowercase. So in the CSS table for the inner-div selector you write the following code:

    Inner-div( display: inline-block; )

    You change the display property from block to inline-block.

    transform/translate method

    Cascading style sheets make it possible to move, skew, rotate, and otherwise transform web elements at will. The transform property is used for this. The values ​​indicate the desired transformation type and degree. In this example we will work with translate:

    transform: translate(50%, 50%);

    The translate function moves an element from its current position left/right and up/down. Two values ​​are passed in brackets:

    • degree of horizontal movement;
    • degree of vertical movement.

    If an element needs to be moved along only one of the coordinate axes, then after the word translate you indicate the name of the axis and in parentheses the amount of the required displacement:

    Transform: translateY(-20%);

    In some manuals you can find transform with vendor prefixes:

    Webkit-transform: translate(50%, 50%); -ms-transform: translate(50%, 50%); transform: translate(50%, 50%);

    In 2018, this is no longer necessary; the property is supported by all browsers, including Edge and IE.

    In order to center the DIV we want, the CSS translate function is written with a value of 50% for the vertical and horizontal axis. This will cause the browser to offset the element from its current position by half its width and height. The width and height properties must be specified:

    Document .nav-bar( display: block; width: 90%; height: 100vh; margin: 0 auto; background: linear-gradient(to left, red, #f06d06); ) .navigation( width: 50%; height: 50%; color: #FFF; border: 1px dashed #F5F2F2; transform: translate(50%, 50%); ) Here goes some text

    Keep in mind that the element to which the transform property is applied moves independently of the objects surrounding it. On the one hand, this is convenient, but sometimes by moving, the DIV can overlap another container. Therefore, this method of centering web components is considered non-standard and is used only in cases of extreme necessity. Transformations according to all CSS canons are used for animation.

    Working with Flexbox layout

    Flexbox is considered a sophisticated way to design web layouts. But if you master it, you will realize that it is much simpler and more pleasant than standard formatting methods. The Flexbox specification is a flexible and incredibly powerful way to handle elements. The name of the module is translated from English as “flexible container”. The values ​​of width, height, and arrangement of elements are adjusted automatically, without calculating indents and margins.

    In previous examples, we already worked with the display property, but we set it to block and inline-block values. To create flex layouts we will use display: flex. First we need a flex container:

    To convert it to a flex container in cascading tables, we write:

    Flex-container( display: flex; )

    All nested objects, but only direct descendants, will be flex elements:

    First second Third Fourth

    If you place a list inside a flex container, then the li list items are not considered flex elements. Flexbox layout will only work on ul:

    Rules for placing flex elements

    To manage flex items, you need justify-content and align-items. Depending on the values ​​you specify, these two properties automatically place objects as needed. If we need to center all nested DIVs, we write justify-content: center, align-items: center and nothing else. The browser will do the rest of the work itself:

    Document .flex-container( display: flex; justify-content: center; align-items: center; ) First Second Third Fourth

    To center text on DIVs that are flex items, you can use the standard text-align technique. Or you can make each nested DIV also a flex container and manage the content using justify-content. This method is much more rational if it contains a variety of content, including graphics, other nested objects, including multi-level lists.