Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of centered layout of elements with variable width and height in css

Shulou Source: shulou.com Published: 2022-05-31 12:38:48 10月04日 Update

This article introduces the relevant knowledge of "how to solve the middle layout of elements with variable width and height in css". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Horizontal center

Common code:

Html:

Parent

Child

Css:

Html, body {margin: 0; width: 100%; height: 100%; .parent {width: 100%; height: 100%; background: # fac3fa; .child {width: 50%; height: 50%; background: # fe9d38;}

Option 1: text-align (parent) + inline-block (child)

Code:

Css:

.parent {text-align: center; .child {display: inline-block;}}

Option 2: block-level element + margin: 0 auto

.child {display: block; / / set margin: 0 auto;} when non-block-level elements

Option 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;}

two。 Vertical center

Common code:

Html:

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;}

Option 1: table-cell (parent) + vertical-align (child)

.parent {display: table-cell; vertical-align: middle;}

Option 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 center

The common code is the same [vertical center]

Common solution 1: absolute + transform

.parent {position: relative; .child {position: absolute; top: 50%; left: 50%; transform: translate (- 50%,-50%);}}

Common option 2: flex

Parent {display: flex; align-items: center; justify-content: center;} "how to solve the central layout of elements with variable width and height in css" is introduced here. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Solutions elements code layout content commonly used more level knowledge practicality learning and then dilemmas realities situations articles cases editing websites industries Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Apple Docker Redmi Shulou Tech Info