search
HomeWeb Front-endHTML TutorialHow to vertically center a div in css

If it is a div with a fixed height and width that is vertically centered on the web page, it must be very simple. I believe everyone can easily write it. But if it is a div with a fixed height and width, how to vertically center it? So how do these divs get vertically centered? In this article, I will summarize

Fixed height and width div vertically centered

enter image description here

As shown above, fixed height and width is very simple, the writing is as follows:

 position: absolute;
 left: 50%;
 top: 50%;
width:200px;
height:100px;
margin-left:-100px;
margin-top:-50px;

No fixed height and width How to vertically center a div

Method 1:

Use a "ghost" pseudo-element (invisible pseudo-element) and inline-block / vertical-align It can be done Centered, very clever. However, this method requires that the element to be centered is inline-block, which is not a truly universal solution.

html is as follows:

<div style="height: 300px;">
    <div>
        <h1 id="haorooms案例题目">haorooms案例题目</h1>
        <p>haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容</p>
    </div>
</div>

css is as follows:

/* This parent can be any width and height */
.block {
  text-align: center;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: &#39;&#39;;
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 50%;
}

Method 2:

You can use the table layout method, but this method also has limitations!

The writing method is as follows:

<table style="width: 100%;">
  <tr>
     <td style="text-align: center; vertical-align: middle;">
          Unknown stuff to be centered.
     </td>
  </tr>
</table>

Since table writing is more time-consuming, you can also use div instead of table. The writing method is as follows:

html:

<div>
   <div>
       Unknown stuff to be centered.
   </div>
</div>
css:
.something-semantic {
   display: table;
   width: 100%;
}
.something-else-semantic {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

Method 3 , The ultimate solution:

The above two methods may have their limitations. The third method I introduced is a more mature method of vertical centering that is not a fixed height and width div! But the method is written in CSS3. For children who want to be compatible with IE8, it is recommended to use the above method!

The method is similar to our fixed height and width, but without margin we use translate()

The demo is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>haorooms不固定高度div写法</title>
    <style>
.center {
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: #000;
  width:50%;
  height: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
}
    </style>
</head>
<body>
    <div></div>
</body>
</html>

My css above is only for the webkit kernel Browser, other kernel browsers are written as follows:

-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);

Regarding the writing method of each browser, you can read my previous article: http://www.haorooms.com/post/css_common

Some pop-up layer styles can also be centered using this method

position: fixed;
top: 50%;
left: 50%;
width: 50%;
max-width: 630px;
min-width: 320px;
height: auto;
z-index: 2000;
visibility: hidden;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);

css3 variable width, high level, and vertical centering

As long as three sentences are needed, you can achieve variable width, high level, and vertical centering.

justify-content:center;//子元素水平居中
align-items:center;//子元素垂直居中
display:-webkit-flex;

Add the above three sentences to the parent element to achieve horizontal and vertical centering of the child elements.

Use margin:auto for vertical centering

The margin value is set to auto, which allows us to allocate the remaining space! We know that block-level elements are set to margin:0 auto; they can be displayed left, right, and centered! Is there any way to make the margin be centered on the top, bottom, left, and right after setting it to margin:auto? By centering the top, bottom, left and right, we can achieve our vertical centering!

The answer is yes, as long as we allow enough space at the top and bottom, we can let margin auto allocate the top and bottom space.

We can use positioning to give the margin enough space up, down, left, and right! Then you can use margin:auto to achieve vertical centering!

The implementation of html is as follows: (make a simple vertical pop-up box)

<div>
    <div></div>
</div>

css code is as follows, it is very simple and has good compatibility. It supports IE8+

.father{position:fixed;width:100%;height:100%;top;0;left:0;background-color:rgba(0,0,0,.7);}
.son{position: absolute;top:0;left:0;bottom:0;right:0;width:50%;height:50%;margin:auto;background-color:red;}

This way Vertical centering can be achieved. Isn’t it very simple? For more exciting content, please pay attention to other related articles on the php Chinese website!


Related reading:

How to realize the pop-up effect of prompt text in CSS3

CSS3 How to realize typing animation in CSS3

How to realize loading animation effect in CSS3

The above is the detailed content of How to vertically center a div in 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
How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How does deepseek official website achieve the effect of penetrating mouse scroll event?How does deepseek official website achieve the effect of penetrating mouse scroll event?Apr 30, 2025 pm 03:21 PM

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

How to modify the playback control style of HTML videoHow to modify the playback control style of HTML videoApr 30, 2025 pm 03:18 PM

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.

What problems will be caused by using native select on your phone?What problems will be caused by using native select on your phone?Apr 30, 2025 pm 03:15 PM

Potential problems with using native select on mobile phones When developing mobile applications, we often encounter the need for selecting boxes. Normally, developers...

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.