Table of Contents
1. Center horizontally? Use text-align
2. margin: auto center
3. table-cell centered
4. Absolute centering
5. Use translate to center
6. Use Flexbox to center
7. Use calc to center
Home Web Front-end HTML Tutorial 7 ways to achieve centering with CSS_html/css_WEB-ITnose

7 ways to achieve centering with CSS_html/css_WEB-ITnose

Jun 24, 2016 am 11:53 AM

Implementing the centering of HTML elements seems simple, but in fact it is not.

Horizontal centering is easy, vertical centering is more difficult, and horizontal and vertical centering is even more difficult. In this era of responsive layout, it is difficult to fix the width and height of elements. I have counted several current methods. This article introduces each step from the shallower to the deeper, using the same HTML code:

<div class="center">
Copy after login</div></div>
<img src="jimmy-choo-shoe.jpg" alt="">
Copy after login</div></div>
</div>
Copy after login</div></div>
Copy after login</div></div>
Copy after login</div></div>

The shoe image below will change but the original size is always 500px × 500px, and the theme background color is used HSL colors

1. Center horizontally? Use text-align

In some scenarios the simple method is the best method

div.center { text-align: center; background: hsl(0, 100%, 97%); }
Copy after login</div></div>
div.center img { width: 33%; height: auto; }
Copy after login</div></div>

But this method cannot center the image vertically: you need to add padding to the div or add margin-top and margin-bottom to the elements in the div

2. margin: auto center

is also horizontally centered, with the same limitations as the first method:

div.center { background: hsl(60, 100%, 97%); }
Copy after login</div></div>
div.center img { display: block; width: 33%; height: auto; margin: 0 auto; }
Copy after login</div></div>

Note that display: block, in this case there must be margin: 0 auto.

3. table-cell centered

Using display: table-cell, you can achieve horizontal and vertical centering. Often it is necessary to add an additional empty element.

<div class="center-aligned">
Copy after login</div></div>
<div class="center-core">
Copy after login</div></div>
<img src="jimmy-choo-shoe.jpg">
Copy after login</div></div>
</div>
Copy after login</div></div>
Copy after login</div></div>
Copy after login</div></div>
</div>
Copy after login</div></div>
Copy after login</div></div>
Copy after login</div></div>

CSS code:

.center-aligned { display: table; background: hsl(120, 100%, 97%);width: 100%; }
Copy after login</div></div>
.center-core { display: table-cell; text-align: center; vertical-align:middle; }
Copy after login</div></div>
.center-core img { width: 33%; height: auto; }
Copy after login</div></div>

Note that width: 100% is to prevent the div from collapsing, and the outer container needs a height to be vertically centered. If the vertically centered element is placed in . body, you need to set height for html and body. Valid in all browsers, including IE8.

4. Absolute centering

A new technology recently promoted by Stephen Shaw can be well compatible with various browsers. The only drawback is that the outer container must declare height

.absolute-aligned {
Copy after login</div></div>
position: relative; min-height: 500px;
Copy after login</div></div>
background: hsl(200, 100%, 97%);
Copy after login</div></div>
.absolute-aligned img {
Copy after login</div></div>
width: 50%;
Copy after login</div></div>
min-width: 200px;
Copy after login</div></div>
height: auto;
Copy after login</div></div>
overflow: auto; margin: auto;
Copy after login</div></div>
position: absolute;
Copy after login</div></div>
top: 0; left: 0; bottom: 0; right: 0;
Copy after login</div></div>

Stephen verified many versions of this code in his article

5. Use translate to center

Chris Coiyer proposed a new method: using CSS transforms . Supports both horizontal and vertical centering:

.center { background: hsl(180, 100%, 97%); position: relative; min-height: 500px; }
Copy after login</div></div>
.center img { position: absolute; top: 50%; left: 50%;
Copy after login</div></div>
transform: translate(-50%, -50%); width: 30%; height: auto; }
Copy after login</div></div>

has the following disadvantages:

  • CSS transform needs to be used specifically for different browsers The prefix (-moz or -o or -webkit)
  • is not valid in lower versions of IE (IE8 and below)
  • The external container needs to set the height (or gain it in some other way ) Because it cannot get the height from its absolutely-positioned content.
  • If the content contains text, the current browser composition technology interprets the text very vaguely.
  • 6. Use Flexbox to center

    This approach will likely become the preferred centering solution once attribute variables and specific prefixes disappear.

    .center { background: hsl(240, 100%, 97%); display: flex; justify-content: center; align-items: center; }
    Copy after login</div></div>
    .center img { width: 30%; height: auto; }
    Copy after login</div></div>

    in In many ways flexbox is the simplest solution, but the constraints are various archaic syntax and lower versions of IE (although display: table-cell is an acceptable solution). Full CSS code:

    .center { background: hsl(240, 100%, 97%);
    Copy after login</div></div>
    display: -webkit-box; /* OLD: Safari, iOS 6 and earlier; Android browser, older WebKit */
    Copy after login</div></div>
    display: -moz-box; /* OLD: Firefox (can be buggy) */
    Copy after login</div></div>
    display: -ms-flexbox; /* OLD: IE 10 */
    Copy after login</div></div>
    display: -webkit-flex; /* FINAL, PREFIXED, Chrome 21+ */
    Copy after login</div></div>
    display: flex; /* FINAL: Opera 12.1+, Firefox 22+ */
    Copy after login</div></div>
    -webkit-box-align: center;
    Copy after login</div></div>
    -moz-box-align: center;
    Copy after login</div></div>
    -ms-flex-align: center;
    Copy after login</div></div>
    -webkit-align-items: center;
    Copy after login</div></div>
    align-items: center;
    Copy after login</div></div>
    -webkit-box-pack: center;
    Copy after login</div></div>
    -moz-box-pack: center;
    Copy after login</div></div>
    -ms-flex-pack: center;
    Copy after login</div></div>
    -webkit-justify-content: center;
    Copy after login</div></div>
    justify-content: center;
    Copy after login</div></div>

    Now that the specification has been formed and browsers support it, I have written extensively on flexbox layout and its uses.

    7. Use calc to center

    In a More versatile than flexbox in some scenarios:

    .center { background: hsl(300, 100%, 97%); min-height: 600px; position:relative; }
    Copy after login</div></div>
    .center img { width: 40%; height: auto; position: absolute; top:calc(50% - 20%); left: calc(50% - 20%); }
    Copy after login</div></div>

    Obviously, calc allows calculations to be performed on the current page layout. In the above example, 50% is the midpoint of the element in the container, but used alone would make the upper left corner of the image in the middle of the

    . We need to pull the width and height back a little, so that the sizes are half of the width and height of the image respectively. The expression is as follows:

    top: calc(50% - (40% / 2)); left: calc(50% - (40% / 2));
    Copy after login</div></div>

    In current browsers, you can find that this technology works best when the content is fixed and the size is known:

    .center img { width: 500px; height: 500px; position: absolute; top:calc(50% - (300px / 2)); left: calc(50% - (300px ? 2)); }
    Copy after login</div></div>

    calc This method also has many potential shortcomings like flexbox: it supports Firefox 4 and higher browsers. For earlier browsers, you need to add a prefix, and IE8 is not supported. The complete code for image centering:

    .center img { width: 40%; height: auto; position: absolute;
    Copy after login</div></div>
    top: -webkit-calc(50% - 20%); left: -webkit-calc(50% - 20%);
    Copy after login</div></div>
    top: -moz-calc(50% - 20%); left: -moz-calc(50% - 20%);
    Copy after login</div></div>
    top: calc(50% - 20%); left: calc(50% - 20%); }
    Copy after login</div></div>

    Of course there are many other methods, such as using pseudo elements to vertically center, understanding these techniques can Let web developers deal with centering issues without getting stuck!

    Original text here

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

    The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

    What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

    The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

    What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

    Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

    How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

    The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

    What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

    The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

    What is the viewport meta tag? Why is it important for responsive design? What is the viewport meta tag? Why is it important for responsive design? Mar 20, 2025 pm 05:56 PM

    The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

    What is the purpose of the <iframe> tag? What are the security considerations when using it? What is the purpose of the <iframe> tag? What are the security considerations when using it? Mar 20, 2025 pm 06:05 PM

    The article discusses the &lt;iframe&gt; tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

    Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Gitee Pages static website deployment failed: How to troubleshoot and resolve single file 404 errors? Apr 04, 2025 pm 11:54 PM

    GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

    See all articles