• Place the block in the center css. Horizontal and vertical alignment of elements in CSS

    Web designers use DIVs in their work every day. Without any understatement, this is the most popular tag. Open the source of any website and you will see that most, if not two thirds of the objects are enclosed in

    . Even with the advent of HTML5 and the emergence of serious competitors in the form of article or header, it continues to be inserted into markup everywhere. Therefore, I suggest you understand the issue of formatting and centering div blocks.

    What is DIV

    The name of the element comes from the English word division, which means division. When writing markup, it is used to break elements into blocks. DIVs enclose groups of content on a web page. For example, images, paragraphs with text. The tag does not affect the display of content in any way and does not carry any semantic load.

    DIV supports all global attributes. But for web design you only need two - class and id. You will only remember about everyone else in exotic cases, and that’s not a fact. The align attribute, which was previously used to center or left align divs, has been deprecated.

    When to use DIVs

    Imagine that the site is a refrigerator, and the DIVs are plastic containers into which you need to sort the contents. You wouldn't put fruit in the same container with liverwurst. You will place each type of product separately. Web content is generated in a similar way.

    Open any website and divide it into meaningful blocks. Header at the top, footer at the bottom, main text in the center. On the side there is usually a smaller column with advertising content or a tag cloud.

    Document

    Now look at each section in more detail. Start with header. The site header has a separate logo, navigation, first-level heading, and sometimes a slogan. Assign each semantic block its own container. This will not only separate the elements in the flow, but also make them easier to format. You'll find it much easier to center an object in a DIV tag by giving it a class or ID.

    Centering DIVs Using Margins

    When rendering web elements, the browser considers three properties: padding, marging and border. Padding is the space between content and its border. Margin - fields that separate one object from another. Border is the lines along the blocks. They can be assigned to all of them at once or only to one side:

    div( border: 1px solid #333; border-left: none; )

    These properties add space between objects and help you align and place them properly. For example, if a block with an image needs to be shifted from the left edge to the center by 20%, you assign a margin-left value of 20% to the element:

    Block-with-img( margin-left: 20%; )

    Elements can also be formatted using their width values ​​and negative padding. For example, there is a block with dimensions 200px by 200px. First, let's assign it an absolute position and move it to the center by 50%.

    Div( position: absolute; left: 50%; )

    Now, to ensure that the centered DIV is positioned perfectly, we give it a negative margin to the left equal to 50% of its width, that is -100 pixels:

    Margin-left: -100px;

    In CSS this is called "air removal". But it has a significant drawback in the need to make constant calculations, which is quite difficult to do for elements with several levels of nesting. If the padding and border-width values ​​are specified, the browser will by default calculate the dimensions of the container as the sum of the thickness of the borders, the padding on the right and left, and the content itself inside, which can also come as a surprise.

    So when you need to center a DIV, use the box-sizing property with the value border-box. This will prevent the browser from adding padding and border values ​​to the overall width of the DIV element. To raise or lower an element, also use negative values. But in this case, they can be assigned to either the top or bottom field of the container.

    How to center a DIV block using automatic margins

    This is an easy way to center large blocks. You simply assign the width of the container and the margin property to auto. The browser will place a block in the middle with equal margins on the left and right, doing all the work itself. As a result, you do not risk getting confused in mathematical calculations and significantly save your time.

    Use the auto-field method when developing responsive apps. The main thing is to assign a width value to the container in em or percentage. The code in the example above will center the DIV and on any device, including mobile phones, it will occupy 90% of the screen.

    Alignment via display property: inline-block

    By default, DIV elements are considered block elements, and their display value is block. For this method you will need to override this property. Only suitable for DIVs with a parent container:

    Any text

    An element with the outer-div class is assigned a text-align property with a value of center, which centers the text inside. But for now the browser sees the nested DIV as a block object. For the text-align property to work, the inner-div must be treated as lowercase. So in the CSS table for the inner-div selector you write the following code:

    Inner-div( display: inline-block; )

    You change the display property from block to inline-block.

    transform/translate method

    Cascading style sheets make it possible to move, skew, rotate, and otherwise transform web elements at will. The transform property is used for this. The values ​​indicate the desired transformation type and degree. In this example we will work with translate:

    transform: translate(50%, 50%);

    The translate function moves an element from its current position left/right and up/down. Two values ​​are passed in brackets:

    • degree of horizontal movement;
    • degree of vertical movement.

    If an element needs to be moved along only one of the coordinate axes, then after the word translate you indicate the name of the axis and in parentheses the amount of the required displacement:

    Transform: translateY(-20%);

    In some manuals you can find transform with vendor prefixes:

    Webkit-transform: translate(50%, 50%); -ms-transform: translate(50%, 50%); transform: translate(50%, 50%);

    In 2018, this is no longer necessary; the property is supported by all browsers, including Edge and IE.

    In order to center the DIV we want, the CSS translate function is written with a value of 50% for the vertical and horizontal axis. This will cause the browser to offset the element from its current position by half its width and height. The width and height properties must be specified:

    Document

    Keep in mind that the element to which the transform property is applied moves independently of the objects surrounding it. On the one hand, this is convenient, but sometimes when moved, the DIV can overlap another container. Therefore, this method of centering web components is considered non-standard and is used only in cases of extreme necessity. Transformations according to all CSS canons are used for animation.

    Working with Flexbox layout

    Flexbox is considered a sophisticated way to design web layouts. But if you master it, you will realize that it is much simpler and more pleasant than standard formatting methods. The Flexbox specification is a flexible and incredibly powerful way to handle elements. The name of the module is translated from English as “flexible container”. The values ​​of width, height, and arrangement of elements are adjusted automatically, without calculating indents and margins.

    In previous examples, we already worked with the display property, but we set it to block and inline-block values. To create flex layouts we will use display: flex. First we need a flex container:

    To convert it to a flex container in cascading tables, we write:

    Flex-container( display: flex; )

    All nested objects, but only direct descendants, will be flex elements:

    First
    Second
    Third
    Fourth

    If you place a list inside a flex container, then the li list items are not considered flex elements. Flexbox layout will only work on ul:

    Rules for placing flex elements

    To manage flex items, you need justify-content and align-items. Depending on the values ​​you specify, these two properties automatically place objects as needed. If we need to center all nested DIVs, we write justify-content: center, align-items: center and nothing else. The browser will do the rest of the work itself:

    Document

    First
    Second
    Third
    Fourth

    To center text on DIVs that are flex items, you can use the standard text-align technique. Or you can make each nested DIV also a flex container and manage the content using justify-content. This method is much more rational if it contains a variety of content, including graphics, other nested objects, including multi-level lists.

    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

    display method as a table, after that we can use the vertical-align property in it (which works differently in different elements).

    Some useful information that should be centrally located.
    #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.

    Cons

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

    Cons

    • 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 be cleared float and displayed in the center.

    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.

    Cons

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

    Cons

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

    Cons

    • 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

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

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

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

      Option 1: Negative indentation.

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

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

      Option 2. Automatic indentation.

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

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

      Option 3. Table.

      Let's ask parent table styles, cell parent Set the text alignment to center. A block we set the line block model. The disadvantages we get are non-working scrollbars, and in general, the aesthetics of table “emulation” are not good.

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

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

      Option 4. Pseudo-element.

      This option is devoid of all the problems listed in the previous methods, and also solves the original problems. The point is that parent set styles pseudo element before, namely 100% height, center alignment and inline block model. It’s the same with block a line block model is placed, centered. To block didn't "fall" under pseudo element, when the dimensions of the first one are greater than parent, indicate parent white-space: nowrap and font-size: 0, after which block cancel these styles with the following - white-space: normal. In this example, font-size: 0 is needed to remove the resulting space between parent And block due to code formatting. The space can be removed in other ways, but it is considered best to simply avoid it.

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

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

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

      Option 5. Flexbox.

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

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

      Option 6. Transform.

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

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

      Option 7. Button.

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

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

      Bonus

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

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

      Today's article aims to show you how to center a div, both horizontally and vertically, using a few CSS tricks. We will also tell you how to center across the entire page or in an individual div element.

      Easily center a DIV element on the page

      This method will work perfectly in all browsers.

      CSS

      Center-div ( margin: 0 auto; width: 100px; )

      Example

      The value auto in the margin property sets the left and right margin to the entire space available on the page. The important thing to remember here is that the centered div element must have a width value set.

      Centering a DIV inside a DIV element the old fashioned way

      This center alignment div method will work in all browsers.

      CSS

      Outer-div ( padding: 30px; ) .inner-div ( margin: 0 auto; width: 100px; )

      HTML

      Example

      The outer div can be placed in any way you like, but the inner div must have a specified width ( width).

      Centering a DIV inside a DIV element using inline-block

      In this method of centering a div within a div, it is not necessary to specify the width of the inner element. It will work in all modern browsers, including IE8.

      CSS

      Outer-div ( padding: 30px; text-align: center; ) .inner-div ( display: inline-block; padding: 50px; )

      HTML

      Example

      The text-align property only works on inline elements. The inline-block value allows the inner div to be displayed as an inline element and also as a block ( inline-block). The text-align property on the outer div element will allow us to center the inner div.

      Center a DIV inside a DIV element horizontally and vertically

      Here margin: auto is used to center the div in the center of the page. The example will work in all modern browsers.

      CSS

      Outer-div ( padding: 30px; ) .inner-div ( margin: auto; width: 100px; height: 100px; )

      HTML

      Example

      The inner div element must have a specified width ( width) and height ( height). The method will not work if the outer div element has a fixed height.

      Center the DIV at the bottom of the page

      Here margin: auto is used to center the div vertically and absolute positioning is used for the outer element. The method will work in all modern browsers.

      CSS

      Outer-div ( position: absolute; bottom: 30px; width: 100%; ) .inner-div ( margin: 0 auto; width: 100px; height: 100px; background-color: #ccc; )

      HTML

      Example

      The inner div must have a width set. The space at the bottom of the page is adjusted using the bottom property of the outer div. You can also center a div at the top of the page by replacing the bottom property with the top property.

      Center DIVs on the page vertically and horizontally

      Here, to center the div, we again use margin: auto and absolute positioning of the outer div. The method will work in all modern browsers.

      CSS

      Center-div ( position: absolute; margin: auto; top: 0; right: 0; bottom: 0; left: 0; width: 100px; height: 100px; )

      Example

      The div element must have a width set ( width) and height ( height).

      Making adaptive centering of a DIV element on the page

      Here, to center the div using CSS, we make the width of the div element responsive so that it responds to changes in window size. This method works in all browsers.

      CSS

      Center-div ( margin: 0 auto; max-width: 700px; )

      Example

      A centered div element must have its max-width property set.

      Centering a DIV inside an element using the inner block properties

      The inner div element here is responsive. This method of centering a div inside a div will work in all browsers.

      CSS

      Outer-div ( padding: 30px; ) .inner-div ( margin: 0 auto; max-width: 700px; )

      HTML

      Example

      The inner div must have its max-width property set.

      Centering two responsive divs next to each other

      Here we have two responsive div elements side by side. This method of placing a div in the center of the screen will work in all modern browsers.

      CSS

      Container ( text-align: center; ) .left-div ( display: inline-block; max-width: 300px; vertical-align: top; ) .right-div ( display: inline-block; max-width: 150px; ) screen and (max-width: 600px) ( .left-div, .right-div ( lef max-width: 100%; ) )

      HTML

      Example

      Here we have several elements with the inline-block property applied, located inside a centered container. This example also uses CSS media queries; that is, if the screen size is less than 600 pixels, then the max-width property for both the left and right div is set to 100%.

      DIV element centered using Flexbox

      Here we center the CSS div using Flexbox. It is intended to facilitate the process of developing user interface designs. This module is supported by Chrome 38+, IE11, Microsoft Edge, Firefox 38+, Safari 9+, Opera 30+, iOS Safari 9+, as well as Android Browser 40+.

      CSS

      Container ( display: flex; align-items: center; justify-content: center; height: 100vh; ) .item ( background-color: #f3f2ef; border-radius: 3px; width: 200px; height: 100px; )