search
HomeWeb Front-endCSS TutorialSummary of various centered CSS layouts

Centering is a situation we often encounter when using css for layout. When using CSS for centering, sometimes a single attribute can do it, and sometimes it requires certain skills to be compatible with all browsers. This article will give a brief introduction to some common methods of centering.

Note: Unless otherwise specified, the methods described in this article are compatible with mainstream browsers such as IE6+, Google, and Firefox.

Let’s start with a few simple, harmless centering methods

1. Set margin to auto

Specifically, The margin-left and margin-right of the element to be centered are both set to auto. This method can only perform horizontal centering and is invalid for floating elements or absolutely positioned elements.

2. Use text-align:center

There is nothing to say about this. It can only be used for inline elements such as pictures, buttons, and text (display is inline or inline-block). etc.) to perform horizontal centering. But it should be noted that in the two weird browsers IE6 and 7, it can horizontally center any element.

3. Use line-height to vertically center a single line of text

Set the line-height of the text to the height of the text parent container, which is suitable for only one line of text. Condition.

4. Use tables

If you are using tables, you don’t have to worry about various centering issues at all. As long as you use td (maybe Using the align="center" and valign="middle" attributes of the th) element can perfectly handle the horizontal and vertical centering of the content inside it, and the table will vertically center the content inside it by default. Centered. If you want to control the centering of table content in CSS, you can use vertical-align:middle for vertical centering. As for horizontal centering, it seems that there is no corresponding attribute in CSS, but in IE6 and 7 we can use text-align:center To horizontally center the elements in the table, text-align:center in IE8+ and Google, Firefox and other browsers only works on inline elements and is invalid on block elements.

CSS布局各种居中总结

CSS布局各种居中总结

In IE6 and 7, you can control the horizontal alignment of the table content through CSS text-algin, regardless of whether the content is in-line Valid for both element and block elements.

CSS布局各种居中总结

But text-align:center in IE8+ and chrome, firefox and other browsers is invalid for block elements, and only the table's own align attribute can be used.

5. Use display:table-cell to center

For those elements that are not tables, we can use display:table-cell to simulate it into a table cells so that you can take advantage of the table's convenient centering feature. For example:

CSS布局各种居中总结

CSS布局各种居中总结

However, this method can only be used on IE8+, Google, Firefox and other browsers, and is invalid for IE6 and IE7. .

The methods mentioned there are all very basic, and naturally cannot be called fancy tricks. Here are some centering methods that require the use of some skills.

6. Use absolute positioning for centering

This method only applies to elements whose width or height we already know.

The principle of absolute positioning for centering is to set the left or top attribute of the absolutely positioned element to 50%. At this time, the element is not centered, but is shifted to the right or left than the centered position. The distance is half the width or height of the element, so you need to use a negative margin-left or margin-top value to bring it back to the centered position. This negative margin value takes half the width or height of the element.

CSS布局各种居中总结

running result:

CSS布局各种居中总结

If you only want to achieve centering in one direction, you can only use left and margin-left to achieve horizontal centering, and use top and margin-top to achieve vertical centering.

7. Another method of using absolute positioning to center

This method also only applies to elements whose width or height we already know, and unfortunately What's more, it only supports IE9+, Google, Firefox and other modern browsers that comply with w3c standards.

Let’s use a piece of code to understand this method:

CSS布局各种居中总结

Running effect:

CSS布局各种居中总结

Here If the width and height of the element are not defined, then its width will be determined by the values ​​​​of left and right, and its height will be determined by the values ​​​​of top and bottom, so the height and width of the element must be set. At the same time, if you change the values ​​of left, right, top, and bottom, you can also offset the element in a certain direction. You can try it yourself.

8. Use floating elements with relative positioning to perform horizontal centering

This method is also a solution for how to horizontally center floating elements, and we don’t need to know what needs to be centered. The width of the element.

The principle of floating centering is: position the floating element relatively to 50% of the width of the parent element, but at this time the element is not centered, but is half its width wider than the centered position. At this time, you need to use relative positioning for the child elements inside it to bring back the extra half of its own width. And because relative positioning is positioned relative to itself, half of its own width only needs to be left or right You can get it by setting it to 50%, so you don't need to know what its actual width is.

This method of using floating and relative positioning to center has the advantage that you don’t need to know the width of the element to be centered, even if the width is constantly changing; the disadvantage is that it requires an extra element to wrap the element to be centered. Elements.

Look at the code:

CSS布局各种居中总结

Running effect:

CSS布局各种居中总结

9. Use font -size to achieve vertical centering

If the height of the parent element is known and you want to center the child elements inside it horizontally and vertically, you can use this method, and the width or height of the child element No need to know.

This method is only valid for IE6 and IE7.

The key point of this method is to set a suitable font-size value for the parent element. The value of this value is the value obtained by dividing the height of the parent element by 1.14, and the child element must be an inline or Inline-block elements need to add the vertical-align:middle attribute.

As for why it is divided by 1.14 instead of other numbers, no one really knows. You just need to remember the number 1.14.

CSS布局各种居中总结

CSS布局各种居中总结

As mentioned in method 5, display:table-cell can be used for centering in current browsers such as IE8+, Firefox and Google. , and the font-size method here is applicable to IE6 and IE7, so combining these two methods can be compatible with all browsers:

CSS布局各种居中总结

CSS布局各种居中总结 CSS布局各种居中总结

In the above example, because the element to be centered is a block element, we also need to turn it into an inline element. If the element to be centered is an inline element such as a picture, you can omit this step.

In addition, if vertical-align:middle is written in the parent element instead of the child element, this is also possible, but the value of 1.14 used when calculating font-size will become approximately 1.5.

The above are some common centering methods. If there are any omissions or errors, please correct them! I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more CSS layout and various centering summaries, please pay attention to the PHP Chinese website for related articles!

Statement
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
The Lost CSS Tricks of Cohost.orgThe Lost CSS Tricks of Cohost.orgApr 25, 2025 am 09:51 AM

In this post, Blackle Mori shows you a few of the hacks found while trying to push the limits of Cohost’s HTML support. Use these if you dare, lest you too get labelled a CSS criminal.

Next Level CSS Styling for CursorsNext Level CSS Styling for CursorsApr 23, 2025 am 11:04 AM

Custom cursors with CSS are great, but we can take things to the next level with JavaScript. Using JavaScript, we can transition between cursor states, place dynamic text within the cursor, apply complex animations, and apply filters.

Worlds Collide: Keyframe Collision Detection Using Style QueriesWorlds Collide: Keyframe Collision Detection Using Style QueriesApr 23, 2025 am 10:42 AM

Interactive CSS animations with elements ricocheting off each other seem more plausible in 2025. While it’s unnecessary to implement Pong in CSS, the increasing flexibility and power of CSS reinforce Lee's suspicion that one day it will be a

Using CSS backdrop-filter for UI EffectsUsing CSS backdrop-filter for UI EffectsApr 23, 2025 am 10:20 AM

Tips and tricks on utilizing the CSS backdrop-filter property to style user interfaces. You’ll learn how to layer backdrop filters among multiple elements, and integrate them with other CSS graphical effects to create elaborate designs.

SMIL on?SMIL on?Apr 23, 2025 am 09:57 AM

Well, it turns out that SVG's built-in animation features were never deprecated as planned. Sure, CSS and JavaScript are more than capable of carrying the load, but it's good to know that SMIL is not dead in the water as previously

'Pretty' is in the eye of the beholder'Pretty' is in the eye of the beholderApr 23, 2025 am 09:40 AM

Yay, let's jump for text-wrap: pretty landing in Safari Technology Preview! But beware that it's different from how it works in Chromium browsers.

CSS-Tricks Chronicles XLIIICSS-Tricks Chronicles XLIIIApr 23, 2025 am 09:35 AM

This CSS-Tricks update highlights significant progress in the Almanac, recent podcast appearances, a new CSS counters guide, and the addition of several new authors contributing valuable content.

Tailwind's @apply Feature is Better Than it SoundsTailwind's @apply Feature is Better Than it SoundsApr 23, 2025 am 09:23 AM

Most of the time, people showcase Tailwind's @apply feature with one of Tailwind's single-property utilities (which changes a single CSS declaration). When showcased this way, @apply doesn't sound promising at all. So obvio

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor