All vertical alignment methods in CSS. Centering the div and other positioning subtleties

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

    Tags: Add tags

    From the author: I welcome you again to the pages of our blog. In today's article I would like to talk about various alignment techniques that can be applied to both blocks and their content. In particular, how to align blocks in css, as well as text alignment.

    Aligning blocks to the center

    In CSS, centering a block is easy. This is the most well-known technique to many, but I would like to talk about it right now, first of all. This means horizontally centered alignment relative to the parent element. How is it done? Let's say we have a container and our experimental subject is in it:

    < div id = "wrapper" >

    < div id = "header" > < / div >

    < / div >

    Let's assume that this is the site header. It does not stretch across the entire width of the window and we need to center it. We write like this:

    #header(

    width / max - width : 800px ;

    margin: 0 auto;

    We need to specify the exact or maximum width, and then write down the key property - margin: 0 auto. It sets the outer margins of our header, the first value determines the top and bottom margins, and the second determines the right and left margins. The value auto tells the browser to automatically calculate padding on both sides so that the element is exactly centered on its parent. Comfortable!

    Text alignment

    This is also a very simple technique. To align all inline elements, you can use the text-align property and its values: left, right, center. The latter centers the text, which is what we need. You can even align a picture in the same way, because it is also an inline element by default.

    Align text vertically

    But this is more complicated. By default, there is no simple, well-known property that easily centers text vertically in a block container. However, there are several techniques that layout designers have come up with over the years.

    Set the block height using padding. The way is not to set an explicit height using height, but to create it artificially using paddings at the top and bottom, which should be the same. Let's create any block and write the following properties to it:

    div( background: #ccc; padding: 30px 0; )

    div(

    background : #ccc;

    padding: 30px 0;

    The background is just to visually show the edges as well as the padding. Now the height of the block is made up of these two indents and the line itself, and it all looks like this:

    Define line-height for the block. I think this is a better way if you need to align one line of text. With it, you can write the height according to normal, using the height property. After that, he also needs to set the row height, the same as the height of the block as a whole.

    div( height: 60px; line-height: 60px; )

    div(

    height: 60px;

    line-height: 60px;

    The result will be similar to the above picture. Everything will work even if you add padding. However, only for one line. If you need more text in the element, then this method will not work.

    Convert a block to a table cell. The essence of this method is that the table cell has the vertical-align: middle property, which centers the element vertically. Accordingly, in this case the block needs to be set to the following:

    div( display: table-cell; vertical-align: middle; )

    div(

    display: table - cell;

    vertical - align: middle;

    This method is good because you can align as much text as you like in the center. But it is better to write display: table to the block in which our div is nested, otherwise it may not work.

    Well, here we come to the last technique for today - this is the vertical alignment of the blocks themselves. It must be said that, again, there is no property that would be intended specifically for this, but there are a few tricks that you should be aware of.

    Set indents as a percentage. If you know the height of a parent element and place another block element inside it, you can center it using percentage padding. For example, the parent has a height of 600 pixels. You place a block in it that is 300 pixels high. How much do you need to back off at the top and bottom to center it? 150 pixels each, which is 25% of the parent’s height.

    This method allows for alignment only when the dimensions allow for calculations. And if your parent is 887 pixels in height, then you won’t be able to accurately record anything, this is already clear.

    Insert an element into a table cell. Again, if we transform the parent element into a table cell, then the block inserted into it will be automatically centered vertically. To do this, the parent just needs to set vertical-align: middle.

    And if, in addition to this, we also write margin: 0 auto, then the element will become horizontally centered!

    There are several fundamentally different ways to center an object vertically using CSS, but choosing the right one can be tricky. We will look at some of them, and also make a small website using the knowledge gained.

    Vertical center alignment is not easy to achieve using CSS. There are many ways and not all work in all browsers. Let's look at 5 different methods and the pros and cons of each. Example.

    1st method

    This method assumes that we set some element to display as a table, then we can use the vertical-align property on it (which works differently in different elements).

    Some useful information that should be centered. #wrapper( display: table; ) #cell( display: table-cell; vertical-align: middle; )

    pros
    • Content can change height dynamically (height is not defined in CSS).
    • Content is not cut off if there is not enough space for it.
    Minuses
    • Doesn't work in IE 7 or less
    • Lots of nested tags
    2nd method

    This method uses absolute positioning of the div, with top set to 50% and margin-top minus half the content height. This implies that the object must have a fixed height, which is defined in the CSS styles.

    Since the height is fixed, you can set overflow:auto; for a div containing content, thus, if the content does not fit, scroll bars will appear.

    Content Here #content ( position: absolute; top: 50%; height: 240px; margin-top: -120px; /* minus half the height */ )

    pros
    • Works in all browsers.
    • There is no unnecessary nesting.
    Minuses
    • When there is not enough space, the content disappears (for example, the div is inside the body and the user has made the windows smaller, in which case the scrollbars will not appear.
    3rd method

    In this method, we will wrap the content div with another div. Let's set its height to 50% (height: 50%;), and the bottom margin to half the height (margin-bottom:-contentheight;). The content will clear float and be centered.

    here is the content #floater( float: left; height: 50%; margin-bottom: -120px; ) #content( clear: both; height: 240px; position: relative; )

    pros
    • Works in all browsers.
    • When there is not enough space (for example, when the window is reduced), the content is not cropped, scrollbars will appear.
    Minuses
    • I can only think of one thing: that an extra empty element is being used.
    4th method.

    This method uses the position:absolute; property. for a div with fixed dimensions (width and height). Then we set its coordinates top:0; bottom:0; , but since it has a fixed height, it cannot stretch and is aligned to the center. This is very similar to the well-known method of horizontally centering a fixed-width block element (margin: 0 auto;).

    Important information. #content( position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; height: 240px; width: 70%; )

    pros
    • Very simple.
    Minuses
    • Doesn't work in Internet Explorer
    • Content will be cut off without scroll bars if there is not enough space in the container.
    5th method

    Using this method, you can center align one line of text. We simply set the text height (line-height) equal to the element height (height). After this, the line will be displayed in the center.

    Some line of text #content( height: 100px; line-height: 100px; )

    pros
    • Works in all browsers.
    • Doesn't cut off text if it doesn't fit.
    Minuses
    • Works only with text (does not work with block elements).
    • If there is more than one line of text, it looks very bad.

    This method is very useful for small elements, such as centering text in a button or text field.

    Now you know how to achieve vertical center alignment, let's make a simple website that will end up looking like this:

    Step 1

    It's always good to start with semantic markup. Our page will be structured as follows:

    • #floater (to center content)
    • #centred (central element)
      • #side
        • #logo
        • #nav (list
        • #content
      • #bottom (for copyrights and all that)

      Let's write the following html markup:

      A Centered Company A Company

      Page Title

      Holistically re-engineer value-added outsourcing after process-centric collaboration and idea-sharing. Energistically simplify impactful niche markets via enabled imperatives. Holistically predominate premium innovation after compelling scenarios. Seamlessly recaptiualize high standards in human capital with leading-edge manufactured products. Distinctively syndicate standards compliant schemas before robust vortals. Uniquely recaptiualize leveraged web-readiness vis-a-vis out-of-the-box information.

      Heading 2

      Efficiently embrace customized web-readiness rather than customer directed processes. Assertively grow cross-platform imperatives vis-a-vis proactive technologies. Conveniently empower multidisciplinary meta-services without enterprise-wide interfaces. Conveniently streamline competitive strategic theme areas with focused e-markets. Phosfluorescently syndicate world-class communities vis-a-vis value-added markets. Appropriately reinvent holistic services before robust e-services.

      Copyright notice goes here

      Step 2

      Now we will write the simplest CSS to place elements on the page. You should save this code in a style.css file. It is to this that the link is written in the html file.

      Html, body ( margin: 0; padding: 0; height: 100%; ) body ( background: url("page_bg.jpg") 50% 50% no-repeat #FC3; font-family: Georgia, Times, serifs; ) #floater ( position: relative; float: left; height: 50%; margin-bottom: -200px; width: 1px; ) #centered ( position: relative; clear: left; height: 400px; width: 80%; max -width: 800px; min-width: 400px; margin: 0 auto; border: 4px solid #666; ) #bottom ( position: absolute; bottom: 0; right: 0; ) #nav ( position: absolute; left: 0; bottom: 0; padding: 20px; bottom: 0; overflow: auto; padding: 20px;

      Before making our content center aligned, we need to set the height of the body and html to 100%. Since the height is calculated without internal and external padding (padding and margin), we set them (padding) to 0 so that there are no scrollbars.

      The bottom margin for a "floater" element is equal to minus half the content height (400px), namely -200px ;

      Your page should now look something like this:

      #centered element width 80%. This makes our site narrower on small screens and wider on larger ones. most sites look indecent on the new wide monitors in the top left corner. The min-width and max-width properties also limit our page so that it doesn't look too wide or too narrow. Internet Explorer does not support these properties. You need to set it to a fixed width.

      Since the #centered element has position:relative set, we can use absolute positioning of the elements within it. Then set overflow:auto; for the #content element so that scrollbars appear if the content does not fit.

      Step 3

      The last thing we'll do is add some styling to make the page look a little more attractive. Let's start with the menu.

      #nav ul ( list-style: none; padding: 0; margin: 20px 0 0 0; text-indent: 0; ) #nav li ( padding: 0; margin: 3px; ) #nav li a ( display: block; background-color: #e8e8e8; margin: 0; border-bottom: 1px solid: right; content: """; font-weight: bold; float: right; margin: 0 2px 0 5px; f8f8f8; border-bottom-color: #777; ) #nav li a:hover::after ( margin: 0 0 0 7px; color: #f93; ) #nav li a:active ( padding: 8px 7px 6px 7px; )

      The first thing we did to make the menu look better was to remove the bullets by setting the list-style:none attribute, and also set the padding and padding, since they vary greatly by default in different browsers.

      Notice that we then specified that the links should be rendered as block elements. Now, when displayed, they are stretched across the entire width of the element in which they are located.

      Another interesting thing we used for the menu is the pseudo-classes:before and:after. They allow you to add something before and after an element. This is a good way to add icons or symbols, such as an arrow at the end of each link. This trick does not work in Internet Explorer 7 and below.

      Step 4

      And last but not least, we will add some screws to our design for even more beauty.

      #centered ( -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; ) h1, h2, h3, h4, h5, h6 ( font-family: Helvetica, Arial, sans- serif; font-weight: normal; color: #666; ) h1 ( color: #f93; border-bottom: 1px solid #ddd; letter-spacing: -0.05em; font-weight: bold; margin-top: 0; padding-top: 0; ) #bottom ( padding: 10px; font-size: 0.7em; color: #f03; ) #logo ( font-size: 2em; text-align: center; color: #999; ) #logo strong ( font-weight: normal; ) #logo span ( display: block; font-size: 4em; line-height: 0.7em; color: #666; ) p, h2, h3 ( line-height: 1.6em; ) a ( color: #f03; )

      In these styles we set rounded corners for the #centered element. In CSS3, this will be done by the border-radius property. This is not yet implemented in some browsers, other than using the -moz and -webkit prefixes for Mozilla Firefox and Safari/Webkit.

      Compatibility

      As you probably already guessed, the main source of compatibility problems is Internet Explorer:

      • The #floater element must have a width set
      • IE 6 has extra padding around menus

      235881 views

      If you cut into any website created on the basis of html, then you will see a certain layered structure. Moreover, its appearance will be similar to a layer cake. If it seems like this to you, then most likely you haven’t eaten for a long time. So first satisfy your hunger, and then we will tell you how to center a div layer on your site:

      Advantages of layout using a tag

      There are two main types of website structure:

      • Tabular;
      • Block.

      Tabular layout was dominant even at the dawn of the Internet. Its advantages include the accuracy of the specified positioning. But, nevertheless, it has obvious shortcomings. The main ones are the length of the code and low loading speed.

      When using table layout, the web page will not be displayed until it is completely loaded. While when using div blocks, the elements are displayed immediately.

      In addition to high loading speed, block construction of a website allows you to reduce the amount of html code 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 construction based on tags is also called layer-by-layer, and the blocks themselves are called layers. This is because when certain property values ​​are used, they can be stacked on top of each other, similar to layers in Photoshop.

      Positioning aids

      In block layout, it is better to position layers using cascading style sheets. The main CSS property responsible for layout is float.
      Property syntax:
      float: left | right | none | inherit
      Where:

      • left – align the element to the left edge of the screen. The flow around the remaining elements occurs on the right;
      • right – alignment on the right, flow around other elements – on the left;
      • none – wrapping is not allowed;
      • inherit – inherits the value of the parent element.

      Let's look at a lightweight example of positioning divs using this property:

      #left ( width: 200px; height: 100px; float: left; background: rgb(255,51,102); ) #right ( width: 200px; height: 100px; float: right; background: rgb(0,255,153); ) Left block Right block


      Now we will try to use the same property to position the third div in the center of the page. But unfortunately float does not have a center value. And when you give a new block an alignment value to the right or left, it is shifted in the specified direction. Therefore, all that remains is to set float: left to all three blocks:


      But this is not the best option either. When the window is made smaller, all layers are lined 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 the div.

      Centering layers

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

      #container ( width: 600px; margin: 0 auto; ) #left ( width: 200px; height: 100px; float: left; background: rgb(255,51,102); ) #right ( width: 200px; height: 100px; float : left; background: rgb(0,255,153); ) #center ( width: 200px; height: 100px; float: left; background: rgb(255,0,0); ) Left block Center block Right block


      The 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 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 regardless of browser window size. Here's what vertically centering a div looks like:


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

      #container ( width: 450px; height:150px; margin:0 auto; background-color:#66CCFF; ) #left ( width: 100px; height: 100px; background: rgb(255,51,102); display: inline-block; vertical-align: middle; margin-left: 35px; ) #right ( width: 100px; height: 100px; background: rgb(0,255,153); display: inline-block; vertical-align: middle; margin-left: 35px; ) #center ( width: 100px; height: 100px; background: rgb(255,0,0); display: inline-block; vertical-align: middle; margin-left: 35px; )


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

      • display: inline-block – aligns a block element into a line and ensures it wraps around another element;
      • vertical-align: middle – aligns the element in the middle relative to the parent;
      • margin-left – sets the left margin.
      How to make a link from a layer

      Strange as it may sound, this is possible. Sometimes a div block as a link may be needed when laying out various types of menus. Let's look at a practical example of implementing a link layer:

      #layer1( width: 500px; height: 100px; background: rgb(51,255,204); border:groove; ) a ( display: block; text-align: center; height: 100%; color: rgb(255,0,51) ; ) Link to our website


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

      Hiding and showing block elements

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

      This is especially true for the main page, the cost of advertising on which is the highest. Therefore, the problem arises of where to “shove” another advertising banner. And here you can’t get away with aligning the div to the center of the page!

      A more rational solution is to make some block hidden. Here is a simple example of such an implementation:

      #layer1( display:block; width: 500px; height: 100px; background: rgb(51,255,204); border:groove; ) function show() ( if(layer1=="none") ( layer1="block"; ) else ( layer1="none"; ) document.getElementById("layer1").style.display=layer1 )

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


      In this example, the location of the div blocks does not change in any way. This uses a simple JavaScript function that changes the value of the css display property after a button is clicked (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, we used one of its values ​​(inline-block ) to center a div within a div.

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

      Centering elements vertically using CSS is a task that presents some difficulty 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 a general description of the problem.

      Vertical Centering Problem

      Horizontal centering is very simple and easy. When the centered element is inline, we use the alignment property relative to the parent element. When the element is block-level, we set its width and automatic setting of 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 made extensive use of the valign attribute, which reinforces the belief that vertical-align is the right way to solve the problem.

      But the valign attribute only works on table cells. And the vertical-align property is very similar to it. 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, alignment is relative to the line height.
      • The table cell uses alignment relative to a value calculated by a special algorithm (usually the row height).

      But unfortunately, the vertical-align property does not work on block-level elements (for example, paragraphs inside a div element). This situation may lead one to think that there is no solution to the problem of vertical alignment.

      But there are other methods for centering block 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 center one line of text vertically. All you have to do is set the line height to be larger than the font size.

      By default, the white space will be distributed evenly at the top and bottom of the text. And the line will be centered vertically. Often the line height is made equal to the element height.

      HTML:

      Required text

      CSS:

      #child ( line-height: 200px; )

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

      Centering an Image Using Line-Height

      What if the content is a picture? Will the above method work? The answer lies in one more 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

      It was mentioned above that the vertical-align property is used for table cells, where it works great. We can display our element as a table cell and use the vertical-align property on it to vertically center the content.

      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 element and output the nested div element as a table cell. You can now use the vertical-align property on the inner container. Everything in it will be centered vertically.

      Unlike the above method, in this case the content can be dynamic as the div element will change size according to 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 element being centered be given a height.

      The example code performs 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 element positioning type. Next, we set the nested div element's top and left properties to 50%, which corresponds to the center of the parent element. But the center is the top left corner of the nested element. 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 in this case is necessary. Then we set the element with 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 borders of the parent element by setting the top, bottom, right, and left properties to 0.

      Setting the margin to auto-generate on all sides will set equal values ​​on all 4 sides and center our nested div element on its parent element.

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

      Equal spaces above and below

      In this method, equal padding is explicitly set at the top and bottom of the parent element.

      HTML:

      Content

      CSS:

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

      The example CSS code sets top and bottom padding for both elements. For a nested element, setting the padding will serve to vertically center it. And the parent element's padding will center the nested element within it.

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

      For example, if the parent element has a height of 400px and the nested element is 100px, then 150px of padding is needed at the top and bottom.

      150 + 150 + 100 = 400

      Using % allows you to leave the calculations to the browser.

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

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

      floating div

      This method uses an empty div element that 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 set its height to 50% of its 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 unwrap the text on the nested element. The example uses clear: both , but it is quite enough to use the same direction as the offset of a floating empty div element.

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

      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 is that none of them is suitable for all cases. You need to analyze the project and choose the one that best suits the requirements.