Horizontal centering css. Horizontal alignment. Absolute positioning and negative margin

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

Horizontal alignment margin: auto

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

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

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

text-align: center

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

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

I'm center aligned

position and negative margin left

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

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

I'm center aligned

display: inline-block + text-align: center

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

Alignment with display: inline-block + text-align: center;

about the author

Vertical alignment line-height To align one line of text, you can use the same height and line spacing

for the parent block. Suitable for buttons, menu items, etc.

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

I'm vertically aligned

position and negative margin up

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

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

display: table-cell

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

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

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

Dynamic alignment of an element on a page

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

Let's connect jQuery to the page:

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

Function alignCenter(elem) ( // code here )

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

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

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

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

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

Application of Flexbox

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

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

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

Related resources Help the project

When creating div blocks, you've probably come across situations where you need to center your div horizontally and vertically using pure CSS. For example, when creating pop-ups with . There are several ways to implement centering, and in this article I'll share my favorite and easiest ways, using CSS or jQuery.

First, the basics:

Horizontal centering in CSS

This is easy to do, we use margin for our div block.

ClassName( margin:0 auto; width:200px; height:200px; )

To center a div block only horizontally, you need to define the width of the block (width), use the auto property for left and right margins. This method will work for all block elements (div, p, h1, and so on...). To apply horizontal centering to inline elements (links, images...), you need to apply the display: block;

Horizontal and vertical centering in CSS

Centering div block horizontally and vertically at the same time, a little more intricate. You need to know the dimensions of the div block ahead of time.

ClassName( width:300px; height:200px; position:absolute; left:50%; top:50%; margin:-100px 0 0 -150px; )

By using absolute positioning of a block, we can detach it from surrounding elements and determine its position in relation to the size of the browser window. Move the div block 50% to the left and top of the window. The top left corner of the block is now in the center of the browser window. All that remains is to place the div block in the center of the page by moving it half its width to the left and half its height up. Hooray! The result was excellent centering of the block on pure css code.

Horizontal and vertical centering with jQuery

As mentioned earlier – CSS method centering only works with fixed dimensions. If the dimensions are not defined, the jQuery method will come to the rescue:

$(window).resize(function())( $(".className").css(( position:"absolute", left: ($(window).width() - $(".className").outerWidth( ))/2, top: ($(window).height() - $(".className").outerHeight())/2 )); // To run a function when the window is loaded: $(window).resize();

The operation of this method is to run the resize() function using the line $(window).resize() . This function works whenever the browser window is resized. We use outerWidth() and outerHeight() because, unlike width() and height() , they include the padding and thickness of the borders in the size they return. Last line, starts the process of centering the div block when the page loads.

The advantage of using this method is that you may not know what size the div is. Main disadvantage– this only works when JavaScript is enabled. Therefore, this method is acceptable for multifunctional interfaces such as VKontakte, Facebook, etc.

As always, feel free to suggest your favorite method for centering blocks by commenting.

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. IN this lesson 6 options presented vertical 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, 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'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 the value being calculated special algorithm(usually the line height is obtained).

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 believe that there is no solution to the vertical alignment problem.

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.

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

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

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:

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

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 left one gets into the center top corner 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 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 at the top and bottom of the parent element.

HTML:

Content

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 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. Downside is the need for calculations.

Note: This method works by installing 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:

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 the floating empty div element.

The top border of the nested div element is directly below lower limit 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 suits the best way according to requirements.

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

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 ; ) Align absolutely positioned blocks

If a block is set to "position: absolute", then it can be positioned relative to its closest parent with "position: relative". To do this, you need all properties ("top ","right","bottom","left") indoor unit assign 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 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 it somewhere nursery rhyme, but I remembered that this may spoil the uniqueness of the article, and our dear readers will 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 is 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 ; ) Alignment 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 shorthand notation 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

With vertical alignment much more problems- 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 the line-height property

In the case when there is only one line in a block, you can achieve its vertical alignment by applying the "line-height" property and setting it to the desired height. To be on the safe side, you should also set “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

The "vertical-align" property also affects table cells. C set value"middle", the content inside the cell is aligned to the center. Certainly, table layout is considered archaic nowadays, but in exceptional cases it can be simulated 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". This will align all elements with "display: inline" that are on the same line relative to 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.

.example-wrapper7 ( display : flex ; height : 300px ; background : #AEB96A ; ) .example-wrapper7 img ( margin : auto ; )

Well, that's all I wanted to write about CSS alignment. Now centering content will not be a problem!

If you cut any website created on html based, then a certain layer-by-layer structure will appear in front of you. Moreover, with his own appearance it will be similar to layer cake. If you think so, then most likely you haven’t eaten for a long time. So first satisfy your hunger, and then we will tell you how to arrange div layer in the center of 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 disadvantages. The main ones are the volume of code and low speed downloads.

When using table layout, the web page will not be displayed until full load. While when using blocks div elements are displayed immediately.

Except high speed loading block construction of the site allows you to reduce the volume several times html code. 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 due to the fact that when using certain values properties, they can be placed one on top of the other like 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. When the window is reduced in size, 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 using the task margin properties zero value 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 edit the above code a little, 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; )


Brief description of the css properties and their values ​​that we used in in this example to center a div inside 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 during layout various types menu. Let's consider practical example implementation of the 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 value of the link block element. And so that the whole height div block became 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.

Especially it concerns home 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 div location blocks does not change at all. Here it is used simplest function JavaScript changing value css properties display after the 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 meanings. 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.