• Horizontal and vertical alignment of elements. Centering a block using CSS

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

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

    1st method

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

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

    Pros
    • Content can change height dynamically (height is not defined in CSS).
    • Content is not cut off if there is not enough space for it.
    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 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 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 A Company

      Page Title

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

      Heading 2

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

      Copyright notice goes here

      Step 2

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

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

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

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

      Your page should now look something like this:

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

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

      Step 3

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

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

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

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

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

      Step 4

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

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

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

      Compatibility

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

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

      235882 views

      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. We position the block with the top and left attributes at 50%, and knowing the height and width of the block in advance, set a negative margin, which is equal to half the size of the block. A huge disadvantage of this option is that you need to count negative indents. Also, the 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 the 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 on the parent, if the latter has 100% width and height set. 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. We set table styles for the parent, and set the text alignment to the center for the parent cell. And we give the block a 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 idea is to style the before pseudo-element on the parent, namely 100% height, center alignment, and inline block model. In the same way, the block itself is set to a line block model, aligned to the center. To prevent the block from “falling” under the pseudo-element when the size of the first one is larger than its parent, we indicate to the parent white-space: nowrap and font-size: 0, after which we cancel these styles for the block with the following - white-space: normal. In this example, font-size: 0 is needed to remove the resulting space between the parent and the 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 the block is 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 the block, and at the same time 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 than the parent, scale it to the size of the parent.
      Example: jsfiddle.net/serdidg/nfqg9rza/3.
      Example with a large picture:

      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 things 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's logical 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, ). The CSS vertical-align property 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 details, centering occurs relative to the height of the row.

      Unfortunately, the vertical-align property cannot be applied to block-level elements, such as a 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.

      Here's the text