1. Horizontal center Public code: html: <div class="parent"> parent <br> <div class="child"> child </div> </div> css: html, body { margin: 0; width: 100%; height: 100%; .parent { width: 100%; height: 100%; background: #fac3fa; .child { width: 50%; height: 50%; background: #fe9d38; } } } Solution 1: text-align (parent) + inline-block (child) Code: .parent { text-align: center; .child { display: inline-block; } } Solution 2: Block-level elements + margin: 0 auto; .child { display: block; // Set margin: 0 auto for non-block-level elements; } Solution 3: absolute + transform .parent { position: absolute; left: 50%; transform: translateX(-50%); } Option 4: flex Note: Due to the use of flex, parent and .parent { display: flex; justify-content: center; } 2. Vertical centering Public code: <div class="parent"> <div class="child"></div> </div> css: html, body { margin: 0; width: 100%; height: 100%; } .parent { display: table-cell; width: 800px; height: 500px; background: #fac3fa; .child { width: 50%; height: 50%; background: #fe9d38; } } Solution 1: table-cell (parent) + vertical-align (child) .parent { display: table-cell; vertical-align: middle; } Solution 2: absolute + transform .parent { position: relative; .child { position: absolute; top: 50%; transform: translateY(-50%); } } Option 3: flex .parent { display: flex; align-items: center; } 3. Horizontal and vertical centering Public code is the same as [vertical center] Common solution 1: absolute + transform .parent { position: relative; .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } } Common solution 2: flex .parent { display: flex; align-items: center; justify-content: center; } The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. |
<<: Detailed explanation of XML syntax
>>: Examples of using && and || operators in javascript
Table of contents introduce 1. Pica 2. Lena.js 3....
Open DREAMWEAVER and create a new HTML. . Propert...
This article mainly introduces 6 solutions to the...
Project requirements require some preprocessing o...
I believe everyone knows HTML and CSS, knows the ...
I've been learning Docker recently, and I oft...
Today, I encountered a problem: the content in the...
Lots of links You’ve no doubt seen a lot of sites ...
Use anti-shake to make DIV disappear when the mou...
We often use click events in the a tag: 1. a href=...
Table of contents render.js part create-context.j...
Preface: In Vue, props can be used to connect ori...
Table of contents 1. Use SVG 2. Use fontAwesome 3...
Quick Reading Why do we need to monitor SQL state...
Table of contents 1. Customize the search bar con...