CSS horizontal center alignment. CSS - Center Align

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: 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

Hello! We continue to master the basics of the HTML language. Let's see what you need to write to align the text to the center, width or edges.

Getting down to business, let's look at how to center text in HTML in three different ways. The last two are linked directly to the style sheet. It can be a CSS file that connects to the pages of the site and defines their appearance.

Method 1 - direct work with HTML

It's actually quite simple. See example below.

Align the paragraph to the center.

If you need to move text fragments in a different way, then instead of the “center” parameter, enter the following values:

  • justify – align text to the width of the page;
  • right – on the right edge;
  • left - to the left.

By analogy, you can move the content that is in the headers (h1, h2) and container (div).

Method 2 and 3 - using styles

The design presented above can be slightly transformed. The effect will be the same. To do this, you need to write the code below.

Text block.

In this form, the code is written directly into the HTML to center the text content.

There is another alternative way to achieve results. You will need to do a couple of steps.

Step 1. In the main code write

Text material.

Step 2. In the included CSS file, enter the following code:

Rovno (text-align:center;)

I note that the word “rovno” is just the name of a class that can be called differently. This is left to the discretion of the programmer.

By analogy, in HTML you can easily make text centered, justified, and aligned to the right or left edge of the page. As you can see, there is far more than one option to achieve your goal.

Just a few questions:

  • Are you doing an information non-profit project?
  • Do you want your website to rank well in search engines?
  • Do you want to earn income online?

If all the answers are positive, then just look at an integrated approach to website development. The information will be especially useful if it runs on the WordPress CMS.

I would like to point out that your own websites are just one of many options for generating passive or active income on the Internet. My blog is dedicated to financial opportunities online.

Have you ever worked in the field of traffic arbitrage, copywriting and other areas of activity that generate primary or additional income through remote collaboration? You can learn about this and much more right now on the pages of my blog.

I will publish a lot of really useful information in the future. Stay in touch. If you wish, you can subscribe to Workip updates by e-mail. The subscription form is located below.

Aligning elements horizontally and vertically can be done in various ways. The choice of method depends on the type of element (block or inline), the type of its positioning, size, etc.

1. Horizontal alignment to the center of the block/page 1.1. If the block has a width: div ( width: 300px; margin: 0 auto; /*center the element horizontally within the parent block*/ )

If you want to align an inline element this way, it needs to be set to display: block;

1.2. If a block is nested within another block and has no/specified width: .wrapper (text-align: center;) 1.3. If the width of the block is set and you need to fix it in the center of the parent block: .wrapper (position: relative; /* set relative positioning for the parent block so that we can then absolutely position the block inside it */) .box ( width: 400px; position: absolute ; left: 50%; margin-left: -200px; /*shift the block to the left by a distance equal to half its width*/ ) 1.4. If the blocks do not have a width specified, you can center them using a parent wrapper block: .wrapper (text-align: center; /*center the contents of the block*/) .box ( display: inline-block; /*arrange the blocks in a row horizontally*/ margin-right: -0.25em; /*remove the right margin between blocks*/ ) 2. Vertical alignment 2.1. If the text occupies one line, for example, for buttons and menu items: .button ( height: 50px; line-height: 50px; ) 2.2. To align a block vertically inside a parent block: .wrapper (position: relative;) .box ( height: 100px; position: absolute; top: 50%; margin: -50px 0 0 0; ) 2.3. Vertical alignment by table type: .wrapper ( display: table; width: 100%; ) .box ( display: table-cell; height: 100px; text-align: center; vertical-align: middle; ) 2.4. If a box has a width and height and needs to be centered on its parent box: .wrapper ( position: relative; ) .box ( height: 100px; width: 100px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; overflow: auto; /*so that the content does not spread out*/ ) 2.5. Absolute positioning at the center of the page/block using CSS3 transformation:

if dimensions are specified for the element

div ( width: 300px; /*set the width of the block*/ height:100px; /*set the height of the block*/ transform: translate(-50%, -50%); position: absolute; top: 50%; left: 50% ; )

if the element has no dimensions and is not empty

Some text here h1 ( margin: 0; transform: translate(-50%, -50%); position: absolute; top: 50%; left: 50%; )

Very often the task is to align a block in the center of the page / screen, and even so that without a Java script, without setting rigid dimensions or negative indents, and so that the scrollbars work for the parent if the block exceeds its size. There are quite a lot of monotonous examples on the Internet on how to align a block to the center of the screen. As a rule, most of them are based on the same principles.

Below are the main ways to solve the problem, their pros and cons. To understand the essence of the examples, I recommend reducing the height/width of the Result window in the examples at the links provided.

Option 1: Negative indentation. We position the block with the top and left attributes at 50%, and knowing the height and width of the block in advance, set a negative margin, which is equal to half the size of the block. A huge disadvantage of this option is that you need to count negative indents. Also, the block does not behave quite correctly when surrounded by scrollbars - it is simply cut off because it has negative margins.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; ) .block ( width: 250px; height: 250px; position: absolute; top: 50%; left : 50%; margin: -125px 0 0 -125px; img (max-width: 100%; height: auto; display: block; margin: 0 auto; border: none; ) )

Option 2. Automatic indentation. Less common, but similar to the first. For the block, we set the width and height, position the attributes top right bottom left to 0, and set margin auto. The advantage of this option is working scrollbars on the parent, if the latter has 100% width and height set. The disadvantage of this method is the rigid setting of dimensions.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; ) .block ( width: 250px; height: 250px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; img (max-width: 100%; height: auto; display: block; margin: 0 auto; border: none; )

Option 3. Table. We set table styles for the parent, and set the text alignment to the center for the parent cell. And we give the block a line block model. The disadvantages we get are non-working scrollbars, and in general, the aesthetics of the “emulation” of the table are not.

Parent ( width: 100%; height: 100%; display: table; position: absolute; top: 0; left: 0; > .inner ( display: table-cell; text-align: center; vertical-align: middle; ) ) .block ( display: inline-block; img ( display: block; border: none; ) )

To add a scroll to this example, you will have to add one more element to the design.
Example: jsfiddle.net/serdidg/fk5nqh52/3.

Option 4. Pseudo-element. This option is devoid of all the problems listed in the previous methods, and also solves the original problems. The idea is to style the before pseudo-element on the parent, namely 100% height, center alignment, and inline block model. In the same way, the block itself is set to a line block model, aligned to the center. To prevent the block from “falling” under the pseudo-element when the size of the first one is larger than its parent, we indicate to the parent white-space: nowrap and font-size: 0, after which we cancel these styles for the block with the following - white-space: normal. In this example, font-size: 0 is needed to remove the resulting space between the parent and the block due to code formatting. The space can be removed in other ways, but it is considered best to simply avoid it.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; white-space: nowrap; text-align: center; font-size: 0; &:before ( height: 100%; display: inline-block; vertical-align: middle; content: ""; ; img (display: block; border: none; ) )

Or, if you need the parent to take up only the height and width of the window, and not the entire page:

Parent ( position: fixed; top: 0; right: 0; bottom: 0; left: 0; overflow: auto; white-space: nowrap; text-align: center; font-size: 0; &:before ( height: 100%; display: inline-block; vertical-align: middle; content: ""; ( display: block; border: none; ) )

Option 5. Flexbox. One of the simplest and most elegant ways is to use flexbox. It does not require unnecessary body movements, quite clearly describes the essence of what is happening, and is highly flexible. The only thing worth remembering when choosing this method is support for IE from version 10 inclusive. caniuse.com/#feat=flexbox

Parent ( width: 100%; height: 100%; position: fixed; top: 0; left: 0; display: flex; align-items: center; align-content: center; justify-content: center; overflow: auto; ) .block ( background: #60a839; img ( display: block; border: none; ) )

Option 6. Transform. Suitable if we are limited by the structure, and there is no way to manipulate the parent element, but the block needs to be aligned somehow. The css function translate() will come to the rescue. A value of 50% absolute positioning will position the top left corner of the block exactly in the center, then a negative translate value will move the block relative to its own dimensions. Please note that negative effects may appear in the form of blurred edges or font style. Also, this method can lead to problems with calculating the position of the block using java-script. Sometimes, to compensate for the loss of 50% of the width due to the use of the CSS left property, the rule specified for the block can help: margin-right: -50%; .

Parent ( width: 100%; height: 100%; position: fixed; top: 0; left: 0; overflow: auto; ) .block ( position: absolute; top: 50%; left: 50%; transform: translate( -50%, -50%); img (display: block; ) )

Option 7. Button. User azproduction option, where the block is framed in a button tag. The button has the property of centering everything that is inside it, namely the elements of the inline and block-line (inline-block) model. In practice I do not recommend using it.

Parent ( width: 100%; height: 100%; position: absolute; top: 0; left: 0; overflow: auto; background: none; border: none; outline: none; ) .block ( display: inline-block; img (display: block;; border: none; ) )

Bonus Using the idea of ​​the 4th option, you can set external margins for the block, and at the same time the latter will be adequately displayed surrounded by scrollbars.
Example: jsfiddle.net/serdidg/nfqg9rza/2.

You can also align the image to the center, and if the image is larger than the parent, scale it to the size of the parent.
Example: jsfiddle.net/serdidg/nfqg9rza/3.
Example with a large picture:

  • 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. Alignment with:

    • 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 block 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.