Horizontal center alignment. CSS centering DIV blocks: horizontal and vertical
Centering elements vertically with using CSS is a task that presents some difficulty for developers. However, there are several methods for solving it, which are quite simple. IN this lesson 6 options presented vertical centering content.
Let's start with general description tasks.
Vertical Centering Problem
Horizontal centering It is very simple and easy to do. 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 installation left and right margins.
Most people using text-align property: , access the vertical-align property to center vertically. Everything looks quite logical. If you have used table templates, you have probably actively used 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 div element). This situation may lead to the idea that solutions to the problem vertical alignment No.
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 vertically center one line of text. All you have to do is set the line height to be larger than the font size.
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 element height.
HTML:
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. Any values can be used larger size text font.
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:
![](https://i2.wp.com/image.png)
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: CSS table is not the same as an HTML table.
HTML:
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 method described above, in in this case the content can be dynamic as the div element will resize 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:
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:
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 margins 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 above and below the parent element.
HTML:
CSS:
#parent ( padding: 5% 0; ) #child ( padding: 10% 0; )
In code Example CSS The top and bottom margins are set 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.
For dynamic change element sizes used relative units measurements. And for absolute units measurements will have to be made 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. Downside is the need for calculations.
Note: This method works by setting margins 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:
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 the 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. A negative value is used to solve the problem margin properties-bottom 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 are suitable for all cases. You need to analyze the project and choose the one that suits in the best possible way according to requirements.
How many copies have already been broken about the task of aligning elements on a page. I bring to your attention a translation of an excellent article with a solution to this problem from Stephen Shaw for Smashing Magazine - Absolute Horizontal And Vertical Centering In CSS.
We all knew about margin: 0 auto; for horizontal centering, but margin: auto; didn't work for vertical. This can be easily fixed by simply setting the height and applying the following styles:
Absolute-Center ( margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; )
I'm not the first to propose this solution, but this approach is rarely used for vertical alignment. In the comments to the How to Center Anything With CSS article, Simon refers to a jsFiddle example that provides great solution for vertical centering. Here are a few more on this topic.
Let's take a closer look at the method.
Advantages
- Cross-browser compatibility (including IE 8-10)
- No additional markup, minimal styling
- Adaptability
- Independence from padding(without box-sizing!)
- Works for images
Flaws
- The height must be specified (see Variable Height)
- It is recommended to set overflow: auto so that the content does not spread
- Doesn't work on Windows Phone
Browser compatibility
The method has been tested and works great in Chrome, Firefox, Safari, Mobile Safari and even IE 8-10. One user mentioned that content is not vertically aligned on Windows Phone.Inside the container
Content placed in a container with position: relative will align perfectly:Absolute-Center ( width: 50%; height: 50%; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; )
Using viewport
Let's set the content to position: fixed and set the z-index:Absolute-Center.is-Fixed ( width: 50%; height: 50%; overflow: auto; margin: auto; position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 999;
Adaptability
The main advantage of the described method is that it works perfectly when the height or width is specified as a percentage, and even understanding min-width/max-width And min-height/max-height.Absolute-Center.is-Responsive ( width: 60%; height: 60%; min-width: 400px; max-width: 500px; padding: 40px; overflow: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0;
Offsets
If the site has a fixed header or you need to make some other indentation, you just need to add code like this to the styles top: 70px; Currently set margin: auto; the content block will be correctly centered in height.You can also align the content to the desired side, leaving centering in height. To do this you need to use right: 0; left: auto; for right alignment or left: 0; right: auto; for left alignment.
Absolute-Center.is-Right ( width: 50%; height: 50%; margin: auto; overflow: auto; position: absolute; top: 0; left: auto; bottom: 0; right: 20px; text-align: right;
Lots of content
To ensure that a large amount of content does not allow the layout to move apart, we use overflow: auto. A vertical scrollbar will appear. You can also add max-height: 100%; if the content does not have additional padding..Absolute-Center.is-Overflow ( width: 50%; height: 300px; max-height: 100%; margin: auto; overflow: auto; position: absolute; top: 0; left: 0; bottom: 0; right : 0; )
![](https://i1.wp.com/habrastorage.org/storage2/06d/0b9/ad9/06d0b9ad95aa8739df02356b205a0d75.png)
Images
This method works great for images too! Let's add style height: auto; then the image will scale along with the container.Absolute-Center.is-Image ( width: 50%; height: auto; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; )
Variable height
The described method requires a given block height, which can be specified as a percentage and controlled using max-height, which makes the method ideal for responsive websites. One way to not specify a height is to use display: table. In this case, the content block is centered regardless of size.There may be problems with cross-browser compatibility, perhaps you should use the table-cell method (described below).
- Firefox/IE8: usage display: table Aligns the block vertically to the top border of the document.
- IE9/10: usage display: table aligns the block left top corner pages.
- Mobile Safari: if the width is set to a percentage, horizontal centering suffers
![](https://i2.wp.com/habrastorage.org/storage2/fb2/fba/c61/fb2fbac61cdc1316969ea02cea2f1028.png)
Other ways
The described method works great in most cases, but there are other methods that may be applicable to solve specific problems.Negative margin
Probably the most popular way. Suitable if the block dimensions are known.Is-Negative ( width: 300px; height: 200px; padding: 20px; position: absolute; top: 50%; left: 50%; margin-left: -170px; /* (width + padding)/2 */ margin- top: -120px; /* (height + padding)/2 */ )
Advantages:
- Cross-browser compatibility
- Minimum code
- Not adaptive
- Layout creeps if there is too much content in the container
- You have to compensate for the indentation or use box-sizing: border-box
Using transform
One of the most simple ways, supports height changes. There is a detailed article on this topic - "Centering Percentage Width/Height Elements" from CSS-Tricks.Is-Transformed ( width: 50%; margin: auto; position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%,-50%); -ms-transform: translate( -50%,-50%); transform: translate(-50%,-50%);
Advantages:
- Variable height
- Minimum code
- Doesn't work in IE 8
- Using Prefixes
- May interfere with other effects with transform
- In some cases, block edges and text are blurred during rendering
Table-cell
Perhaps one of the best and easiest ways. Described in detail in the article "Flexible height vertical centering with CSS, beyond IE7" by 456bereasttreet. The main drawback is the additional markup: three elements are required:
CSS:
.Pos-Container.is-Table ( display: table; ) .is-Table .Table-Cell ( display: table-cell; vertical-align: middle; ) .is-Table .Center-Block ( width: 50%; margin: 0 auto;
Advantages:
- Variable height
- Layout does not work when large quantities text in block
- Cross-browser compatibility
- Complex structure
Flexbox
The future of CSS, flexbox will solve many of today's layout problems. This is written in detail in a Smashing Magazine article called Centering Elements with Flexbox.Pos-Container.is-Flexbox ( display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-align: center; - moz-box-align: center; -ms-flex-align: center; -webkit-align-items: center; -webkit-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center)
Advantages:
- Content can be any height or width
- Can be used in more complex cases
- No support for IE 8-9
- Requires container or styles in body
- Requires a wide variety of prefixes to correct operation in modern browsers
- Possible performance issues
Bottom line
Each method has advantages and disadvantages. Essentially, the choice comes down to choosing which browsers should be supportedI 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, for vertical alignment there is a special vertical-align property in CSS with multiple values. 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.
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 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 to see their boundaries.
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 indoor unit aligned horizontally, but not vertically:
http://jsfiddle.net/c1bgfffq/
Why did this happen? The thing is that the vertical-align property affects the alignment the element itself, not its contents(except when it is applied to table cells). Therefore the application of this property To external element didn't give anything. Moreover, applying this property to the inner element will also do nothing, since line blocks(inline-block) 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/
Obvious minus this decision– 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 the 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 downside of the solution is that it is applicable only in a limited number of cases when the heights of both blocks are known.
Alignment using 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/
Also this technique can also be used to align multi-line text if you override 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/
Minus this method is that the height of the external block must be known.
Alignment using "stretch"
This method can be used when the height of the external block is unknown, but the height of the internal block is known.To do this you need:
- set to external unit relative positioning, and to the internal – absolute;
- 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.
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 with 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 with transform
This method is similar to the previous one, but it can be used when the height of the indoor unit 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 in previous method Couldn't you set the value as a percentage? 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
Most modern way 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 that's all! Beautiful, isn't 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.
A designer sometimes has a question: how to center elements vertically? And this causes certain problems. However, there are several methods for centering elements vertically, and each of these methods is quite simple. This article describes some of these methods.
To see each method in action, click on the demo button or on the image.
Let's discuss some of the issues that prevent vertical centering.
Vertical-Align
Horizontally centering an element is fairly easy to implement (using CSS). An inline element can be centered horizontally by giving its parent container a text-align property of center . When an element is a block element, to center it, you just need to set the width (width) and set the values of the right (margin-right) and left (margin-left) margins to auto .
Regarding text: many people are starting to use the vertical-align property for centering. It makes sense and my first choice would be the same. To center an element in a table, you can use the valign attribute.
However, the valign attribute only works when applied to a cell (for example, ). CSS property vertical-align can be applied to a cell and some inline elements.
- The text is centered relative to line-height ( line spacing).
- In relation to the table, without going into detail, centering occurs relative to the height of the row.
Unfortunately, the vertical-align property cannot be applied to block elements, such as paragraph (p) inside a div tag.
However, there are other methods for centering elements vertically, and you can still use the vertical-align property where needed. Which method to use depends on what you are going to center.
Line spacing or Line-height
This method should only be used when you need to center a line of text. To do this, you need to set the line-height (line spacing) of the element that contains text to greater than the font size.
By default, there is equal space above and below the text, so the text is centered vertically.
In this case, it is not necessary to specify the height of the parent element.
#child ( line-height: 200px; )
This method works in all browsers, but do not forget that it should be used for a line of text. If your text spans more than one line, use a different method. The value of the line-height property can be anything, but not less than the font height. In practice, this method works great for centering a horizontal menu.
CSS Method Using Table Properties
As I already wrote, the contents of a cell can be centered using the property CSS vertical-align. The parent element must be represented as a table, the child element must be designated as a cell and the vertical-align property must be applied to it with the value middle . This way, any content in the child element will be centered vertically. The CSS code is given below.
#parent ( display: table;) #child ( display: table-cell; vertical-align: middle; )
Unfortunately, this method does not work in older versions of the IE browser. If you require browser support for IE6 and below, add a display: inline-block declaration to the child element.
#child ( display: inline-block; )
Absolute positioning and negative margin
This method is designed for block-level elements and works in all browsers. You need to set the height of the element that needs to be centered.
Below is the code where the child element is centered using this method.
#parent (position: relative;) #child ( position: absolute; top: 50%; left: 50%; height: 30%; width: 50%; margin: -15% 0 0 -25%; )
First you need to position the parent and child elements. We then set the child element's offset to 50% relative to the top and left side of the parent element, thereby centering the child element relative to the parent element. However, our manipulations will center the top-right corner of the child element in the center of the parent element, which, of course, does not suit us.
Our task: to move the child element up and to the left, relative to the parent element, so that the child element is visually centered vertically and horizontally. This is why you need to know the height and width of the child element.
So, we should give the child element a negative top and left margin equal to half, respectively, the width and height of the child element.
Unlike the first two methods, this method is intended for block-level elements. The method works in all browsers, but the content may exceed the height of the parent element and extend beyond its boundaries. This method works best when the height and width of the elements are fixed.
Absolute positioning of a child element
As in the previous method, the parent and child elements are positioned relative and absolute, respectively.
In the CSS code I center the child element both vertically and horizontally, however you can only use vertical centering.
#parent (position: relative;) #child ( position: absolute; top: 0; bottom: 0; left: 0; right: 0; width: 50%; height: 30%; margin: auto; )
The idea of this method is that you can position a child element using top , left , right , bottom property values equal to 0. Since our child element is smaller than the parent element, it will not be able to “stick” to the parent element.
The margin values for all four sides of the child element are zero, which centers the element vertically relative to the parent. Unfortunately, this method has the same disadvantages as the previous method: it is necessary to fix the height and width of the child, lack of support for older IE browsers.
Bottom and top margins are equal
In this method, we explicitly assign equal padding (bottom and top) to the parent element, which visually centers the child element vertically.
#parent ( padding: 5% 0; ) #child ( padding: 10% 0; )
I use relative sizes. If the block sizes are fixed, then you will need to do some mathematical calculations.
For example, if the parent element has a height of 400px and the child is 100px, then you should set the top and bottom padding to 150px.
150 + 150 + 100 = 400
floating div
This method involves an empty float block that controls the vertical position of the child element. The floating div needs to be placed before the child element, see the HTML code below.
#parent (height: 250px;) #floater ( float: left; height: 50%; width: 100%; margin-bottom: -50px; ) #child ( clear: both; height: 100px; )
First we move the floating block to the left (or right) and give it a height of 50% of its parent. This way the floating block will fill the top half of the parent element.
Since the block is floating, it is removed from the general flow of the document, therefore, the child block should be assigned the clear property with the value both . I set the value to both , but you can use a value that matches the positioning direction of the floating element.
Currently, the top edge of the child element lies directly below the bottom edge of the floating element. We need to raise the child element to half the height of the floating element. To do this, just set the negative bottom margin for the floating block to 50%.
Works in all browsers. The disadvantage of this method is that it requires an empty block and requires knowing the height of the child element.
Every layout designer is constantly faced with the need to align content in a block: horizontally or vertically. There are several good articles on this subject, but they all offer a lot of interesting, but few practical options, which is why you have to spend extra time to highlight the main points. I decided to present this information in a form that is convenient for me, so as not to google anymore.
Aligning blocks with known sizes
The easiest way to use CSS is to align blocks that have a known height (for vertical alignment) or width (for horizontal alignment).
Alignment using padding
Sometimes you can not center an element, but add borders to it using the " padding".
For example, there is a picture of 200 by 200 pixels, and you need to center it in a block of 240 by 300. We can set the height and width of the outer block = 200px, and add 20 pixels at the top and bottom, and 50 at the left and right.
.example-wrapper1 ( background : #535E73 ; width : 200px ; height : 200px ; padding : 20px 50px ; )Aligning Absolutely Positioned Blocks
If the block is set to " position: absolute", then it can be positioned relative to its closest parent with "position: relative". This requires all properties (" top","right","bottom","left") of the inner block to assign the same value, as well as "margin: auto".
*There is a nuance: The width (height) of the inner block + the value of left (right, bottom, top) should not exceed the dimensions of the parent block. It is safer to assign 0 (zero) to the left (right, bottom, top) properties.
.example-wrapper2 ( position : relative ; height : 250px ; background : url(space.jpg) ; ) .cat-king ( width : 200px ; height : 200px ; position : absolute ; top : 0 ; left : 0 ; bottom : 0 ; right : 0 ; margin : auto ; background : url(king.png) ;Horizontal alignment
Alignment using "text-align: center"
To align text in a block there is a special property " text-align". When set to " center"Each line of text will be aligned horizontally. For multi-line text, this solution is used extremely rarely; more often this option can be found for aligning spans, links or images.
I once had to come up with some text to show how text alignment works using CSS, but nothing interesting came to mind. At first I decided to copy a children’s rhyme somewhere, but I remembered that this might spoil the uniqueness of the article, and our dear readers would not be able to find it on Google. And then I decided to write this paragraph - after all, the point is not with it, but the point is in alignment.
.example-text ( text-align : center ; padding : 10px ; background : #FF90B8 ; )It's worth noting that this property will work not only for text, but also for any inline elements ("display: inline").
But this text is aligned to the left, but it is in a block that is centered relative to the wrapper.
.example-wrapper3 ( text-align : center ; background : #FF90B8 ; ) .inline-text ( display : inline-block ; width : 40% ; padding : 10px ; text-align : left ; background : #FFE5E5 ; )Aligning blocks using margin
Block elements with a known width can easily be aligned horizontally by setting them to "margin-left: auto; margin-right: auto". Usually the abbreviation is used: " margin: 0 auto" (any value can be used instead of zero). But this method is not suitable for vertical alignment.
.lama-wrapper ( height : 200px ; background : #F1BF88 ; ) .lama1 ( height : 200px ; width : 200px ; background : url(lama.jpg) ; margin : 0 auto ; )This is how you should align all blocks, where possible (where fixed or absolute positioning is not required) - it is the most logical and adequate. Although this seems obvious, I have sometimes seen scary examples with negative indents, so I decided to clarify.
Vertical alignment
Vertical alignment is much more problematic - apparently, this was not provided for in the CSS. There are several ways to achieve the desired result, but all of them are not very beautiful.
Alignment with line-height property
In the case when there is only one line in a block, you can achieve its vertical alignment by using the " line-height" and setting it to the desired height. For reliability, it is worth setting also "height", the value of which will be equal to the value of "line-height", because the latter is not supported in all browsers.
.example-wrapper4 ( line-height : 100px ; color : #DC09C0 ; background : #E5DAE1 ; height : 100px ; text-align : center ; )It is also possible to achieve block alignment with several lines. To do this, you will have to use an additional wrapper block and set the line height to it. An internal block can be multi-line, but must be "inline". You need to apply "vertical-align: middle" to it.
.example-wrapper5 ( line-height : 160px ; height : 160px ; font-size : 0 ; background : #FF9B00 ; ) .example-wrapper5 .text1 ( display : inline-block ; font-size : 14px ; line-height : 1.5 ; vertical-align : middle ; background : #FFFAF2 ; color : #FF9B00 ;The wrapper block must have "font-size: 0" set. If you don't set the font size to zero, the browser will add a few extra pixels. You will also have to specify the font size and line height for the inner block, because these properties are inherited from the parent.
Vertical alignment in tables
Property " vertical-align" also affects table cells. With the value set to "middle", the content inside the cell is aligned to the center. Of course, table layout is considered archaic nowadays, but in exceptional cases you can simulate it by specifying " display: table-cell".
I usually use this option for vertical alignment. Below is an example of layout taken from a completed project. It is the picture that is centered vertically in this way that is of interest.
.one_product .img_wrapper ( display : table-cell ; height : 169px ; vertical-align : middle ; overflow : hidden ; background : #fff ; width : 255px ; ) .one_product img ( max-height : 169px ; max-width : 100 % ; min-width : 140px ; display : block ; margin : 0 auto ;It should be remembered that if an element has a “float” set other than “none”, then it will in any case be block (display: block) - then you will have to use an additional block wrapper.
Alignment with an additional inline element
And for inline elements you can use " vertical-align: middle". Moreover, all elements with " display: inline" that are on the same line will align with a common center line.
You need to create an auxiliary block with a height equal to the height of the parent block, then the desired block will be centered. To do this, it is convenient to use the pseudo-elements:before or:after.
.example-wrapper6 ( height : 300px ; text-align : center ; background : #70DAF1 ; ) .pudge ( display : inline-block ; vertical-align : middle ; background : url(pudge.png) ; background-color : # fff ; width : 200px ; height : 200px ; .riki ( display : inline-block ; height : 100% ; vertical-align : middle ; )Display: flex and alignment
If you don't care much about Explorer 8 users, or care so much that you're willing to insert a piece of extra javascript for them, then you can use "display: flex". Flex boxes are great at dealing with alignment issues, and just write "margin: auto" to center the content inside.
So far, I have practically never encountered this method, but there are no special restrictions for it.
Well, that's all I wanted to write about CSS alignment. Now centering content will not be a problem!