In front-end development, vertical centering of elements is a very common requirement. For some beginners, this may be a very troublesome thing. However, there are actually many ways to achieve vertical centering using CSS. Let’s introduce some of the more practical methods below.
Method 1: Absolute positioning margin:auto
This is a relatively common method. It uses the CSS absolute positioning feature and sets the values of top and left, and sets the margin Set to auto to achieve vertical centering.
First, you need to position the element to be centered using absolute positioning:
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* 其它样式 */ }
Then, set the margin to auto to achieve horizontal centering:
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: auto; /* 其它样式 */ }
This The advantage of this method is that it is relatively easy to understand and implement, and its compatibility is also very good. Note, however, that it only works if the height of the element you want to vertically center is known.
Method 2: Flex Layout
Flex layout is a newly added layout mode in CSS3. It makes vertical centering easy.
.parent { display: flex; justify-content: center; align-items: center; } .child { /* 其它样式 */ }
The advantage of this method is that it is very convenient and intuitive, and its compatibility is relatively good. However, it should be noted that when it needs to be compatible with older versions of browsers, some compatibility processing needs to be added.
Method Three: Table Layout
Table layout is also an older CSS layout method, which can also be used to achieve vertical centering.
.parent { display: table; height: 100%; } .child { display: table-cell; vertical-align: middle; /* 其它样式 */ }
The advantage of this method is that it is also very compatible and easy to implement. However, it should be noted that it is not suitable for all scenarios. If high adaptability and flexibility are required, there may be some problems.
Method 4: Line-height
There is also a relatively simple method, which is to use Line-height to achieve vertical centering.
.parent { height: 300px; /* 定义容器高度 */ line-height: 300px; /* 容器高度与line-height相同,使文本垂直居中 */ text-align: center; /* 水平居中 */ } .child { display: inline-block; /* 行内块级元素 */ vertical-align: middle; /* 垂直居中 */ /* 其它样式 */ }
The advantage of this method is that it is very simple and has good compatibility. However, it should be noted that it only applies to inline elements or inline block elements, and only applies to vertically centered text scenarios.
Summary
The above introduces some common CSS methods to achieve vertical centering. Different methods are suitable for different scenarios and need to be selected according to actual needs. Also note that sometimes a combination of methods may be needed to achieve vertical centering. I hope this article can help you achieve vertical centering more easily.
The above is the detailed content of How to achieve vertical centering in css. For more information, please follow other related articles on the PHP Chinese website!

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

Notepad++7.3.1
Easy-to-use and free code editor
