search
HomeWeb Front-endCSS Tutorial4 commonly used CSS methods to achieve vertical centering

This time I will bring you 4 commonly used CSS methods to achieve vertical centering. What are the precautions for CSS to implement vertical centering? . Here are practical cases, let’s take a look.

Line-heightline-heightAchieving vertical centering of a single line of text

I used to think that the vertical centering of a single line of text requires the height Set the same value as the row height, but there is no need to set the height. In fact, the text itself appears centered on a line. Without setting a height, the row height expands the height.

<style>
.test{
    line-height: 50px;
    background-color: lightblue;
}    
</style>
<p>测试文字</p>

Settingsvertical-align:middle to achieve vertical centering

【1】Set the display of the parent element to table-cell

By setting vertical-align:middle for the table-cell element, all its child elements can be vertical Centered. This is similar to the vertical centering of cells in tables

[Note] If IE7-browser supports it, you can change it to

table structure

[Note] The p set to table-cell cannot use floating or absolute positioning, because floating or absolute positioning will make the element have block-level element characteristics, thereby losing the vertical alignment function of the table-cell element.

If you need floating or absolute positioning processing, you need to add a layer of p outside.

<style>
.parent{
  display: table-cell;
  vertical-align: middle;
}
</style>
<p>
    </p><p>我是有点长的有点长的有点长的有点长的测试文字</p>   

4 commonly used CSS methods to achieve vertical centering

[2] If the child element is a picture, set the row height of the parent element instead of the height, and set the font-size of the parent element to 0.

vertical-align: The explanation of middle is that the midpoint of the element is aligned with the baseline of the parent element plus 1/2 the height of the letter X in the parent element. Because the character X is not vertically centered in the em box, and the high and low positions of the character X in each font are inconsistent.

So, when the font size is larger, the difference is more obvious. When font-size is 0, it is equivalent to setting the font size of character X to 0, so complete vertical centering can be achieved.

<style>
.parent{
  line-height: 100px;
  font-size: 0;
}
.child{
  vertical-align: middle;
}
</style>
<p>
  <img  class="child lazy" src="/static/imghwm/default1.png" data-src="http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/img1.gif" alt="4 commonly used CSS methods to achieve vertical centering" >  
</p>

4 commonly used CSS methods to achieve vertical centering

【3】Achieve vertical centering effect by adding new elements

Set the height of new elements to the parent height , the width is 0, and the inline-block element of vertical-align:middle is also set to be vertically centered. Since the space between the two elements is parsed, you need to set font-size:0 at the parent level, and then set font-size to the required value at the child level; if the structural requirements are not strict, you can display the two elements in one line , then there is no need to set font-size:0.

<style>
.parent{
  height: 100px;
  font-size: 0;
}
.child{
  display: inline-block;
  font-size: 20px;
  vertical-align: middle;
}
.childSbling{
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
</style>
<p>
  </p><p>我是比较长的比较长的多行文字</p>
  <i></i> 

Three ideas: Vertical centering through absolute positioning

[1]If the child element has an uncertain height, use top50% with translateY (-50%) can achieve centering effect.

The percentage of the translate function is relative to its own height, so top:50% combined with translateY(-50%) can achieve the centering effect.

[Note] IE9-browser does not support;

[Note] If the height of the child element is known, the translate() function can also be replaced with margin-top: a negative height value.

<style>
.parent{
  position:relative;
}
.child{
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
</style>
<p>
  </p><p>测试文字</p>

[2] If the height of the child element is fixed, combine the absolutely positioned box model attributes to achieve the centering effect

<style>
.parent{
  position: relative;
}
.child{
 position: absolute;
 top: 0;
 bottom: 0;
 margin: auto 0;
 height: 50px;
}
</style>
<p>
  </p><p>测试文字</p>

In horizontal center alignment, put a layer of p on the outer layer of the element and set absolute, and set the negative margin-left or relative negative left attribute of the element to achieve the horizontal centering effect. But since margin is relative to the width of the containing block, margin-top:-50% gets the width instead of -50% of the height, so it is not feasible; for the relative percentage value, the height of the containing block is auto In this case, chrome, safari and IE8+ browsers do not support setting the percentage top value of the element, so it is not feasible.

Idea 4: Use flexible box modelflex to achieve vertical centering

[注意] IE9-浏览器不支持

【1】在伸缩容器上设置侧轴对齐方式align-items: center

<style>
.parent{
  display: flex;
  align-items: center;
}
</style>
<p>
    </p><p>测试文字</p>   

【2】在伸缩项目上设置margin: auto 0

<style>
.parent{
  display: flex;
}
.child{
  margin: auto 0;
}
</style>
<p>
    </p><p>测试文字</p>   

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

css3的pointer-events使用详解

focus-within的使用详解

CSS3做出无缝轮播广告

The above is the detailed content of 4 commonly used CSS methods to achieve vertical centering. 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
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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

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

EditPlus Chinese cracked version

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

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

SublimeText3 English version

Recommended: Win version, supports code prompts!