Center Align DIV. Horizontal and vertical alignment of elements

Centering elements vertically with CSS is a challenge for developers. However, there are several methods for solving it, which are quite simple. This lesson presents 6 options for vertically centering content.

Let's start with general description tasks.

Vertical centering problem

Horizontal centering is very simple and easy. When the centered element is inline, use the alignment property relative to the parent element. When the element is a block element, we set its width and automatic installation left and right margins.

Most people, when using the text-align: property, refer to the vertical-align property for vertical centering. Everything looks quite logical. If you've used table templates, you've probably used the valign attribute extensively, which reinforces the belief that vertical-align is the right way to go.

But the valign attribute only works on table cells. And the vertical-align property is very similar. It also affects table cells and some inline elements.

The value of the vertical-align property is relative to the parent inline element.

  • In a line of text, the alignment is relative to the line height.
  • The table cell uses alignment with respect to the value calculated by a special algorithm (usually the line height is obtained).

But unfortunately, the vertical-align property doesn't work on block-level elements (such as paragraphs inside a div element). This situation may lead to the idea that there is no solution to the problem of vertical alignment.

But there are other methods of centering block-level elements, the choice of which depends on what is being centered in relation to the outer container.

line-height method

This method works when you want to vertically center one line of text. All you have to do is set the line height to be larger than the font size.

By default, free space will be distributed evenly above and below the text. And the line will be centered vertically. Often the line height is made equal to the height of the element.

HTML:

Desired text

CSS:

#child ( line-height: 200px; )

This method works in all browsers, although it can only be used for a single line. The value of 200 px in the example is chosen arbitrarily. You can use any value larger than the text font size.

Centering an image with line-height

What if the content is an image? Will the above method work? The answer lies in another line of CSS code.

HTML:

CSS:

#parent ( line-height: 200px; ) #parent img ( vertical-align: middle; )

The value of the line-height property must be greater than the height of the image.

CSS Table Method

As mentioned above, the vertical-align property applies to table cells, where it works great. We can render our element as a table cell and use the vertical-align property on it to center the content vertically.

Note: A CSS table is not the same as an HTML table.

HTML:

Content

CSS:

#parent (display: table;) #child ( display: table-cell; vertical-align: middle; )

We set the table output to the parent div and render the nested div as a table cell. Now you can use the vertical-align property on the inner container. Everything in it will be centered vertically.

In contrast to the method described above, this case the content can be dynamic, as the div element will resize to fit its content.

The disadvantage of this method is that it does not work in older versions of IE. You have to use the display: inline-block property for the nested container.

Absolute positioning and negative margins

This method also works in all browsers. But it requires that the centered element be given a height.

The example code does both horizontal and vertical centering at the same time:

HTML:

Content

CSS:

#parent (position: relative;) #child ( position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; )

First, we set the positioning type of the elements. Then, on the nested div, set the top and left properties to 50%, which is the center of the parent element. But the top left corner of the nested element gets centered. Therefore, you need to lift it up (half the height) and move it to the left (half the width), and then the center will coincide with the center of the parent element. So knowing the height of the element is necessary in this case. Then we give the element negative top and left margins equal to half the height and width, respectively.

This method does not work in all browsers.

Absolute positioning and stretching

The example code performs vertical and horizontal centering.

HTML:

Content

CSS:

#parent (position: relative;) #child ( position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 50%; height: 30%; margin: auto; )

The idea behind this method is to stretch the nested element to all 4 of the parent element's borders by setting the top, bottom, right, and left properties to 0.

Setting the margins on all sides to auto will set the values ​​on all 4 sides to be equal, and will bring our nested div element to the center of the parent element.

Unfortunately, this method does not work in IE7 and below.

Equal padding top and bottom

This method explicitly sets equal padding above and below the parent element.

HTML:

Content

CSS:

#parent ( padding: 5% 0; ) #child ( padding: 10% 0; )

In the CSS code for the example, top and bottom padding is set for both elements. For a nested element, setting the padding will serve to vertically center it. And the padding of the parent element will center the nested element in it.

Relative units are used to dynamically resize elements. And for absolute units of measurement, you will have to do the calculations.

For example, if the parent element is 400px high and the nested element is 100px high, then 150px of padding is required at the top and bottom.

150 + 150 + 100 = 400

Using % allows the calculations to be left to the browser.

This method works everywhere. The downside is the need for calculations.

Note: This method works by setting the margin of the element. You can also use margins within an element. The decision to apply margins or padding should be made depending on the specifics of the project.

floating div

This method uses an empty div element, which floats and helps control the position of our nested element in the document. Note that the floating div is placed before our nested element in the HTML code.

HTML:

Content

CSS:

#parent (height: 250px;) #floater ( float: left; height: 50%; width: 100%; margin-bottom: -50px; ) #child ( clear: both; height: 100px; )

We offset the empty div to the left or right and give it a height of 50% of the parent element. This way it will fill the top half of the parent element.

Since this div is floating, it is removed from the normal flow of the document and we need to unwind the nested element. The example uses clear: both , but it suffices to use the same direction as the offset of the floating empty div element.

The top border of the nested div element is directly below the bottom border of the empty div element. We need to move the nested element up by half the height of the floating empty element. To solve the problem, a negative value of the margin-bottom property for a floating empty div element is used.

This method also works in all browsers. However, using it requires an additional empty div element and knowledge of the height of the nested element.

Conclusion

All methods described are easy to use. The difficulty lies in the fact that none of them is suitable for all cases. It is necessary to analyze the project and choose the one that best suits the requirements.

If you cut any site created on the basis of html , then you will see a certain layered structure. And their appearance it will be similar to a layer cake. If you think so, then most likely you have not eaten for a long time. So satisfy your hunger first, and then we'll show you how to center the div layer on your site:

Benefits of layout using a tag

There are two main types of site structure building:

  • tabular;
  • Block.

Tabular layout has been dominant since the dawn of the Internet. Its advantages include the accuracy of the given positioning. But, nevertheless, it has obvious shortcomings. The main ones are the bulk of the code and the low download speed.

When using tabular layout, the web page will not be displayed until it is fully loaded. Whereas when using div blocks, the elements are rendered immediately.

In addition to high loading speed, block building of the site allows you to reduce the amount of html code by several times. Including through the use of CSS classes.

However, tabular layout should be used to structure the display of data on the page. A classic example of its use is the display of tables.

Block building based on tags

also called layered, and the blocks themselves are layers. This is because when using certain property values, they can be placed one on top of the other, similar to layers in Photoshop.

Positioning aids

In block layout, layer positioning is best done using cascading style sheets. The main CSS property responsible for the position

, is a float.
Property syntax:
float: left | right | none | inherit,
Where:

  • left - aligns the element to the left edge of the screen. The rest of the elements wrap around to the right;
  • right - alignment on the right, wrapping the rest of the elements - on the left;
  • none - wrapping is not allowed;
  • inherit - inherit the value of the parent element.

Consider a lightweight example of positioning divs using this property:

Left block


Now let's try to use the same property to position the third div in the center of the page. But unfortunately float doesn't have a center value. And when a new block is given an alignment value to the right or left, it shifts in the specified direction. Therefore, it remains only to set all three blocks to float: left :


But this is not the best option. When the window is reduced, all layers line up in one row vertically, and when the size is increased, they stick to the left edge of the window. So we need a better way to center divs.

Centering Layers

In the following example, we will use a container layer to place the rest of the elements on. This solves the problem of shifting blocks relative to each other when the window is resized. Centering the container in the middle is done by setting the margin properties to zero value for the margins from the top edge and auto on the sides (margin: 0 auto ):

Left block

central block


This same example shows how you can center a div horizontally. And if you slightly edit the above code, you can achieve vertical alignment of the blocks. To do this, you just need to change the length of the container layer (reduce it). That is, after editing its css, the class should look like this:

After the change, all blocks will line up strictly in a row in the middle. And their position will not change at any size of the browser window. This is what a div centered vertically looks like:


In the following example, we used a number of new css properties to center the layers inside the container:


A brief description of the css properties and their values ​​that we used in this example to center a div inside a div :

  • display: inline-block - lines up a block element into a line and wraps it with another element;
  • vertical-align: middle - aligns the element in the middle relative to the parent;
  • margin-left - sets the margin to the left.

How to make a link from a layer

As strange as it sounds, it is possible. Sometimes a div block as a link may be needed when layout various kinds menu. Consider practical example link layer implementations:

Link to our site


In this example, using the line display: block , we set the link to the value of a block element. And to make the entire height of the div become a link, set height : 100%.

Hiding and showing block elements

Block elements provide more options for expanding the functionality of the interface than the outdated tabular layout. It often happens that the design of the site is unique and recognizable. But you have to pay for such an exclusive lack of free space.

Especially it concerns home page, the cost of advertising on which is the highest. Therefore, there is a problem where to "shove" another advertising banner. And here you can't get away with aligning the div to the center of the page!

More rational decision is to make some block hidden. Here is a simple example of such an implementation:

This is the magic button. Clicking on it will hide or show the hidden block.


In this example, the position of the div blocks does not change in any way. Here we use the simplest JavaScript function that changes the value of the css display property after clicking on the button ( onclick event).

Display syntax:
display:block | inline | inline block | inline table | list item | none | run-in | table | table caption | table cell | table-column-group | table-column | table-footer-group | table-header-group | table row | table-row-group

As you can see, this property can take on many values. Therefore, it is very useful and can be used to position elements. In one of the previous examples, using one of its values ​​( inline block) we have implemented the alignment of the div inside the div in the center.

We used two values ​​for the display property to hide and show the layer.

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

This article presents some turnkey solutions to make it easier to center 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 - Align block to center

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

...
...

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 percent.

Parent ( position: relative; ) .child ( position: absolute; /* width and height of the 2 box in % */ height: 50%; width: 50%; /* Values ​​are determined based 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 an inline (display: inline) or inline-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 box in this example has a fixed height, which is set using the line-height CSS 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 presenting 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 of any other cool tricks or useful out-of-the-box alignment solutions, please share them in the comments.

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 make text center three in HTML different ways. The last two are related directly to the style sheet. It can be a CSS file that is connected to the pages of the site and sets their appearance.

Method 1 - work directly with HTML

In fact, everything is quite simple. See example below.

Align the paragraph to the center.

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

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

By analogy, you can move the content that is in the headers (h1, h2), 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 text content.

Is there some more Alternative option to achieve result. You will need to do a couple of things.

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 center the text, justify it, and align it to the right or left of the page. As you can see, there is far from one option to achieve the goal.

Just a few questions:

  • Are you doing an informational non-commercial project?
  • Do you want your site to perform well? search engines?
  • Do you want to earn income online?

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

I would like to note that your own sites are just one of the 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 activities that bring in the main or additional income with remote cooperation? You can find out about this and much more right now on the pages of my blog.

Ahead I will publish still not a little realistic useful information. Stay in touch. If you wish, you can subscribe to Workip updates by e-mail. The subscription form is located below.

Vlad Merzhevich

Due to the fact that the contents of the 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 to the web page as a whole. In general, alignment is mainly necessary to establish a visual connection between different elements, as well as their grouping.

Vertical centering

One way to show the visitor the focus and title of the site is to use a splash page. This is the first page, on which, as a rule, there is a flash-intro or a picture expressing the main idea of ​​the site. The image is also a link to other sections of the site. It is required to place this picture 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 equal to 100% (example 1).

Example 1: Centering a picture

alignment

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

To set the table height to 100%, remove, the code is no longer valid.

Using the width and height for the entire available area of ​​the web page ensures that the contents of the table will be aligned strictly in the center of the browser window, regardless of its size.

Horizontal alignment

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

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

Top alignment

To specify the alignment of cell contents to the top, for the tag it is required 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 is also more convenient to change through styles. In particular, cell alignment is specified by the vertical-align and text-align properties (example 3).

Example 3: Apply styles for alignment

alignment

Column 1 Column 2

To shorten the code, this example uses selector grouping 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 bottom is used instead of top .

Center alignment

By default, the contents of a cell are aligned to the center of their vertical, so in case different heights columns need to be set to top alignment. 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 on the right edge. For such an arrangement of elements, you need a table with three cells. The outer cells should have the same size, in the middle cell the alignment is done in the center, and in the right cell - on the right edge (example 4). This number of cells is required in order to ensure that the formula is centered.

Example 4: Formula Alignment

alignment

(18.6)

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

Aligning form elements

Tables are useful for positioning form fields, especially when they are interspersed with text. One of the design options for the form, which is designed to enter a comment, is shown in Fig. 3.

In order for the text near the form fields to be right-aligned, and the form elements themselves to be left-aligned, you 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
Comment

In this example, the align="right" attribute has been added for cells that require right alignment. In order for the "Comment" label to be located at the top border of the multiline text, the corresponding cell is set to top-aligned using the valign attribute.

Loading...
Top