Home Web Front-end CSS Tutorial Let'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

Aug 03, 2020 pm 04:59 PM
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>
Copy after login

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>
Copy after login

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;
			}
Copy after login

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;
			}
Copy after login

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 );
		   }
Copy after login

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>
Copy after login

The public css is as follows

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

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;
			}			
Copy after login

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;
	        }
Copy after login

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%);
			}
Copy after login

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;
			}
Copy after login

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 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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

See all articles