Get the App
SLTechnology News&Howtos  ›  Development  › 

How to achieve the effect of centering up and down in css

Shulou Source: shulou.com Published: 2022-06-01 12:16:06 11月24日 Update

This article will explain in detail how to achieve the upper and lower center effect in css. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Inline elements of a single line

You only need to set the line height of the element in a single line to be equal to the height of the box.

# father {

Width:500px

Height:300px

Background-color:skyblue

}

# son {

Background-color:green

Height:300px

}

I am a single-line in-line element

Effect:

1556519521438598.jpg

Inline elements of multiple lines

Use to set display:table-cell; and vertical-align:middle; for the parent element

# father {

Width:500px

Height:300px

Background-color:skyblue

Display:table-cell

Vertical-align:middle

}

# son {

Background-color:green

}

I'm a multi-line inline element.

Effect:

1556519558892168.jpg

Block level element

Option 1: use location

First, set the parent element to relative positioning, then set the child element to absolute positioning, and set the top:50%, of the child element to center the upper left corner of the child element vertically.

Set height: set half the height of the margin-top:- element of the absolute child element px; or set transform:translateY (- 50%)

# father {

Width:500px

Height:300px

Background-color:skyblue

Position:relative

}

# son {

Height:100px

Background-color:green

Position:absolute

Top:50%

Margin-top:-50px

}

I'm a block element.

Variable height: use css3 to add attribute transform:translateY (- 50%)

# father {

Width:500px

Height:300px

Background-color:skyblue

Position:relative

}

# son {

Width:100px

Background-color:green

Position:absolute

Left:50%

Transform:translateY (- 50%)

}

I'm a block element.

Effect:

1556519576485117.jpg

Solution 2: use flexbox layout to implement (height can be varied)

With the flexbox layout, you only need to add the attribute display:flex;align-items:center to the parent element of the block element to be processed

# father {

Width:500px

Height:300px

Background-color:skyblue

Display:flex

Align-items:center

}

# son {

Width:100px

Height:100px

Background-color:green

}

I'm a block element.

This is the end of the article on "how to achieve the upper and lower center effect in css". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Element multiline effect height article positioning up and down attributes layout scheme more good practical content block upper left corner article box knowledge reference Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Redmi Apple NVidia MariaDB