search
HomeWeb Front-endCSS TutorialLet's talk about the method of realizing horizontal and vertical centered layout with CSS

Let's talk about the method of realizing horizontal and vertical centered layout with CSS

During a recent interview, the interviewer asked about the horizontal and vertical centering layout method of CSS. As a newbie in front-end, I was undoubtedly confused. I quickly looked up the information when I was free. Let me analyze it and share it with you to avoid falling into pitfalls.

First of all, let’s explain html and some basic css styles, I won’t go into details below!
html

<body>
		<div class="div1">
			<div class="box  size">垂直水平居中</div>
		</div>
	</body>

The public css code is as follows

<style type="text/css">
			/* 公共样式 */
			.div1{
				width: 300px;
				height: 300px;
				border:1px solid aqua;
				
			}
			.box{
				background: #00FFFF;
			}
			.box.size{
				width:100px;
				height:100px;
			}
</style>

These css styles will be included by default in the subsequent introduction, so I won’t go into details!

1. absolute and margin auto (commonly used)

Similarly, the width and height of the centered element must be fixed, and the width and height of the child elements need to be known
In this way, by setting the distance in all directions to 0, and then setting the margin to auto, you can center it in all directions

.div1{
				position: relative;
			}
			.box{
				position: absolute;
				top:0;
				left: 0;
				right: 0;
				bottom: 0;
				
				margin: auto;
			}

2. Absolute and margin (negative value)

Let’s briefly talk about the principle. Absolute positioning is used. The percentage of absolute positioning is relative to the width and height of the parent element, so we can center the element based on this principle. . But please note: absolute positioning is based on the upper left corner of the child element, but if you want the child element to be displayed in the center, you must solve this problem.
At this time, you can use the negative value of margin to achieve the effect. When the margin is negative, the element is positioned in the opposite direction. In this way, we can set the margin of the sub-element to half the width and height of the sub-element. . (PS: The disadvantage is that the width and height of the child element must be obtained)

.div1{
				position: relative;
			}
			.box{
				top: 50%;
				left: 50%;
				position: absolute;
				margin-top: -50px;
				margin-left: -50px;
			}

3. Absolute and calc

also require the width and height of the child element Fixed, and knowing width and height, css3 has computed properties.
The percentage of top is based on the upper left corner of the element minus half of the width (PS: depends on the compatibility of calc)

.div1{
			   position: relative;
		   }
		   .box{
			   position: absolute;
			   top: calc(50% - 50px ); 
				/* 减号前后没有空格,该样式不生效*/
			   left: calc(50% - 50px );
		   }

When I was writing this code, I discovered an interesting thing, calc (50%-50px) If there are no spaces before and after the minus sign, the style will not take effect. If you add spaces, it will take effect normally. I don’t know the specific reason emmmmm

below The method can be set without knowing the width and height of the child elements.

html is modified to:

<body>
		<div class="div1">
			<div class="box">水平垂直居中,不需要子元素固定宽高</div>
		</div>
	</body>

The public css is as follows

	.div1{
				width: 300px;
				height: 300px;
				border: 1px solid red;
			}
			.box{
				background: #00FFFF;
			}

4. Flex (commonly used)

flex is a modern layout solution that only requires a few lines of code to achieve the centering effect

.div1{
				display: flex;
				justify-content: center;
				align-items: center;
			}			

5. line-height

Using the centering attribute of inline elements can also achieve horizontal and vertical centering. Set the box as an inline element and use text-align to achieve horizontal centering or vertical-align (PS: This method requires resetting the text display to the desired effect in the child element)

          .div1{
				line-height: 300px;
				text-align: center;
				font-size: 0px;
			}
			.box{
				font-size: 10px;
				display: inline-block;
				vertical-align: middle;
				line-height:initial;
				/* 修正文字 */
			 	text-align: left;
	        }

6. Absolute and transform

does not require fixed width and height of child elements, but depends on the compatibility of translate2d

           .div1{
				position: relative;
			}
			.box{
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%,-50%);
			}

7. css-table

The new table attribute of css can change the display effect of ordinary elements to table elements, and can also achieve horizontal centering

           .div1{
				display:table-cell;
				text-align: center;
				vertical-align: middle;
			}
			.box{
				display:inline-block;
			}

The above are some of the centered layout methods I have summarized. If there are any other methods, you are welcome to add them!

Personal feeling: I prefer absolute margin auto, flex, absolute and transform. It is best to use flex on the mobile terminal. I like absolute margin auto# on the PC terminal.

## Recommended related tutorials:

CSS video tutorial, CSS3 video tutorial

The above is the detailed content of Let's talk about the method of realizing horizontal and vertical centered layout with CSS. For more information, please follow other related articles on the PHP Chinese website!

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
Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

What is CSS Grid?What is CSS Grid?Apr 30, 2025 pm 03:21 PM

CSS Grid is a powerful tool for creating complex, responsive web layouts. It simplifies design, improves accessibility, and offers more control than older methods.

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

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.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version