• Horizontal and vertical alignment of elements. Center alignment: CSS layout

    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 various methods, as well as the pros and cons of each of them. 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 centered.
    #wrapper( display: table; ) #cell( display: table-cell; vertical-align: middle; )

    Pros

    • Content can change height dynamically (height is not defined in CSS).
    • Content is not cut off if there is not enough space for it.

    Cons

    • Doesn't work in IE 7 or less
    • Lots of nested tags

    2nd method

    This method uses absolute positioning div, whose top is set to 50%, and the top margin (margin-top) to 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 scroll bars will not appear.

    3rd method

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

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

    Pros

    • Works in all browsers.
    • When there is not enough space (for example, when the window is reduced), the content is not cropped, scrollbars will appear.

    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 horizontal alignment centered on 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.

      Please note that we then specified that the links should appear 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 good way add icons or symbols such as an arrow at the end of each link. This trick does not work in Internet Explorer 7 and below.

      Step 4

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

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

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

      Compatibility

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

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

      235881 views

      Generally centering HTML elements on the page - this is not a difficult matter. In some cases... web developers have to rack their brains to find the best solution.

      Centering the elements horizontally is not so difficult; vertically it already raises questions, but combining them in general can be perplexing. In the era adaptive design, we are rarely clear about the exact dimensions of certain elements. I counted 6 in various ways centering elements using CSS. Let's start with simple examples, let's finish with more complex ones. It will work with the same HTML code:

      Horizontal alignment using text-align

      Sometimes the simplest solution is the best:

      Div.center ( text-align: center; background: hsl(0, 100%, 97%); ) div.center img ( width: 33%; height: auto; )

      There is no vertical centering here: for this you will need to add the margin-top and margin-bottom properties to the div.

      Centering with margin: auto

      Another solution for horizontal alignment:

      Div.center ( background: hsl(60, 100%, 97%); ) div.center img ( display: block; width: 33%; height: auto; margin: 0 auto; )

      Please note that for this method you need to set the display: block property.

      Centering using table-cell

      By using display: table-cell, we can ensure that the element is centered both vertically and horizontally. But here we need to nest the image in another div element.

      Center-aligned ( display: table; background: hsl(120, 100%, 97%);width: 100%; ) .center-core ( display: table-cell; text-align: center; vertical-align: middle; ) .center-core img ( width: 33%; height: auto; )

      For everything to work correctly, the div needs to be set to width: 100%. To center the element vertically, we will use standard techniques by setting the height. Works everywhere, including IE8+.

      Absolute alignment

      A very interesting solution. The idea is that you need to set the height of the outer container:

      Absolute-aligned ( position: relative; min-height: 500px; background: hsl(200, 100%, 97%); ) .absolute-aligned img ( width: 50%; min-width: 200px; height: auto; overflow : auto; margin: auto; position: top: 0; bottom: 0;

      Center using translate

      A new solution that uses CSS transformations. Provides both horizontal and vertical alignment:

      Center ( background: hsl(180, 100%, 97%); position: relative; min-height: 500px; ) .center img ( position: absolute; top: 50%; left: 50%; transform: translate(-50 %, -50%); width: 30%; height: auto)

      There are several disadvantages:

      • CSS transform property requires browser prefixes
      • Doesn't work in older versions of IE (8 and below)
      • The outer container needs to be given a height.
      • If there is text inside the container, it may be a little blurry.

      Centering using the flex display type

      Probably the simplest option.

      Center ( background: hsl(240, 100%, 97%); display: flex; justify-content: center; align-items: center; ) .center img ( width: 30%; height: auto; )

      Doesn't work in all versions of IE (although you can protect yourself by using display: table-cell in addition). Full CSS:

      Center ( background: hsl(240, 100%, 97%); display: -webkit-box; /* Safari, iOS 6 and earlier versions; Android, old WebKit */ display: -moz-box; /* Firefox (may be buggy) */ display: -ms-flexbox; /* IE 10 */ display: -webkit-flex; /* Chrome 21+ */ display: flex; /* Opera 12.1+, Firefox 22+ */ -webkit-box-align: center; -moz-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; -webkit-box-pack: center; -moz-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; )

      Centering using calc

      In some cases, this method is more versatile than using flexbox:

      Center ( background: hsl(300, 100%, 97%); min-height: 600px; position: relative; ) .center img ( width: 40%; height: auto; position: absolute; top:calc(50% - 20%); left: calc(50% - 20%);

      It's very simple, we can calculate the dimensions we need depending on the entire page layout. The calculations are very simple, 50% is the center point of the container, but our task is to place the left top corner images. Next, subtract half the height and width of the image. The formula is as follows:

      Top: calc(50% - (40% / 2)); left: calc(50% - (40% / 2));

      In practice you may find that this method works fine if we know the sizes of the elements:

      Center img ( width: 500px; height: 500px; position: absolute; top:calc(50% - (300px / 2)); left: calc(50% - (300px - 2)); )

      This method is supported by Firefox, starting from version 4, you will need to register browser prefixes. Doesn't work in IE 8. Full code:

      Center img ( width: 40%; height: auto; position: absolute; top: -webkit-calc(50% - 20%); left: -webkit-calc(50% - 20%); top: -moz-calc (50% - 20%); left: -moz-calc(50% - 20%); top: calc(50% - 20%);

      I hope these methods are enough for you to find the best solution for yourself.

    • CSS
    • HTML
    • I think many of you who have had to deal with layout have encountered the need to align elements vertically and know the difficulties that arise when aligning an element to the center.

      Yes, 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.
      To illustrate, consider the following example.

      There are two div element, 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 so that we can see their borders.

      Outer ( width: 200px; height: 200px; text-align: center; vertical-align: middle; background-color: #ffc; ) .inner ( display: inline-block; width: 100px; height: 100px; background-color : #fcc )
      After applying the styles we will see that 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 gave nothing to the external element. Moreover, applying this property to an inner element will also do nothing, since inline-blocks are aligned vertically relative to adjacent blocks, and in our case we have one inline block.

      There are several techniques to solve this problem. Below we will take a closer look at each of them.

      Alignment using a table

      The first solution that comes to mind is to replace the outer block with a table of one cell. In this case, the alignment will be applied to the contents of the cell, that is, to the inner block.


      http://jsfiddle.net/c1bgfffq/1/

      The obvious disadvantage of this solution is that, from a semantic point of view, it is incorrect to use tables for alignment. The second disadvantage is that creating a table requires adding another element around the outer block.

      The first minus can be partially removed by replacing the table and td tags with div and setting the table display mode in CSS.


      .outer-wrapper ( display: table; ) .outer ( display: table-cell; )
      However, the outer block will still remain a table with all the ensuing consequences.

      Alignment using indents

      If the heights of the inner and outer blocks are known, then 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:

      1. set relative positioning to the external block, and absolute positioning to the internal block;
      2. 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;
      3. set the vertical padding of the inner block to auto.
      .outer ( position: relative; ) .inner ( height: 100px; position: absolute; top: 0; bottom: 0; margin: auto 0; )
      http://jsfiddle.net/c1bgfffq/4/

      The idea behind this technique is that setting a height for a stretched and absolutely positioned block forces the browser to calculate vertical margins in equal proportion if their value 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 was it impossible to set the value as a percentage in the previous method? Since percentage margin values ​​are calculated relative to the parent element, a value of 50% would be half the height of the outer box, and we would need to raise the inner box to half its own height. The transform property is perfect for this.

      The disadvantage of this method is that it cannot be used if the indoor unit has absolute positioning.

      Alignment with Flexbox

      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.

      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 minus this option is that you need to count negative padding. 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 set the width and height, position with the top attributes 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 the “emulation” of the table are not.

      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 set, 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 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 css properties left can be helped by the rule specified for the block: 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: