


CSS 9 ways to achieve vertical and horizontal centering with variable width and height (dry information)
There are common flex, transform, absolute, etc. There is also a CSS3 grid layout. There are also pseudo-element methods. Yes, you read that right, ::after and ::before can also achieve centering.
1. flex
Everyone’s first reaction may be flex. Because its writing method is simple and intuitive enough, and there is no problem with compatibility. It is the first choice for centering on mobile phones.
<div class="wrapper flex-center"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; } .flex-center { display: flex; justify-content: center; align-items: center; }
Using two key attributes: justify-content and align-items, both are set to center to achieve centering.
It should be noted that the flex-center here must be hung on the parent element to make the only child element centered.
2. flex margin
This is a variant of the flex method. The parent element is set to flex, and the child element is set to margin: auto;. It can be understood that the child elements are "squeezed" into the middle by the surrounding margins.
<div class="wrapper"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; display: flex; } .wrapper > p { margin: auto; }
3. Transform absolute
This combination is often used to center the image.
<div class="wrapper"> <img src="/static/imghwm/default1.png" data-src="test.png" class="lazy" alt="CSS 9 ways to achieve vertical and horizontal centering with variable width and height (dry information)" > </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; position: relative; } .wrapper > img { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
Of course, you can also move the relative positioning of the parent element wrapper into the child element img and replace the absolute positioning. The effect is the same.
4. table-cell
Use the table's cell centering effect to display. Like flex, it needs to be written on the parent element.
<div class="wrapper"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; display: table-cell; text-align: center; vertical-align: middle; }
5. Absolute The values in the four directions are equal
Use absolute positioning layout, set margin:auto;, and set the values of top, left, right, and bottom Just be equal (not necessarily all 0).
<div class="wrapper"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; position: relative; } .wrapper > p { width: 170px; height: 20px; margin: auto; position: absolute; top: 0; left: 0; right: 0; bottom: 0; }
This method is generally used for pop-up layers, and the width and height of the pop-up layer need to be set.
6. writing-mode
This method can change the display direction of text, such as changing the display direction of text to vertical direction.
<div class="wrapper"> <div class="wrapper-inner"> <p>horizontal and vertical</p> </div> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; writing-mode: vertical-lr; text-align: center; } .wrapper > .wrapper-inner { writing-mode: horizontal-tb; display: inline-block; text-align: center; width: 100%; } .wrapper > .wrapper-inner > p { display: inline-block; margin: auto; text-align: left; }
There are still some minor flaws in compatibility, but most browsers, including mobile phones, already support writing-mode writing.
7, grid
Like a table, a grid layout allows us to align elements by rows or columns. However, in terms of layout, grids are more possible or simpler than tables.
<div class="wrapper"> <p>horizontal and vertical</p> </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; display: grid; } .wrapper > p { align-self: center; justify-self: center; }
But it is not as good as flex in terms of compatibility, especially the IE browser, which only supports IE10 and above.
8. Can ::after
pseudo elements also be used to achieve centering? It feels quite magical, look at the following example:
<div class="wrapper"> <img src="/static/imghwm/default1.png" data-src="test.png" class="lazy" alt="CSS 9 ways to achieve vertical and horizontal centering with variable width and height (dry information)" > </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; text-align: center; } .wrapper::after { content: ''; display: inline-block; vertical-align: middle; height: 100%; } .wrapper > img { vertical-align: middle; }
The horizontal direction is easy to understand. In the vertical direction, it can be understood as ::after pulling the img down to the middle.
9, ::before
The other is the magic performed together with font-size: 0;.
<div class="wrapper"> <img src="/static/imghwm/default1.png" data-src="test.png" class="lazy" alt="CSS 9 ways to achieve vertical and horizontal centering with variable width and height (dry information)" > </div>
.wrapper { width: 300px; height: 300px; border: 1px solid #ccc; text-align: center; font-size: 0; } .wrapper::before { display: inline-block; vertical-align: middle; font-size: 14px; content: ''; height: 100%; } .wrapper > img { vertical-align: middle; font-size: 14px; }
font-size: 0; The secret is that you can eliminate the gaps between labels. In addition, because pseudo-elements are matched with the most basic CSS writing methods, there is no risk of compatibility.
Recommended tutorial: "CSS Tutorial"
The above is the detailed content of CSS 9 ways to achieve vertical and horizontal centering with variable width and height (dry information). For more information, please follow other related articles on the PHP Chinese website!

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

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.

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

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

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

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.

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.

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.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

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