“This is the second day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

Hi, I’m Smooth, a sophomore front-end enthusiast who wants to become a front-end development engineer

This is an article aboutcssCenter knowledge summary, as long as these are understood, center this aspect of the interview is no problem

It’s hard to get around the positioning problem when it comes to CSS, especially if the box is centered. Center is divided into horizontal center and vertical center, there are many ways to achieve, I will list them one by one.

Horizontal center

1. Inline element: text-align: center
Block element: margin: 0 auto
3. Absolute element: left: 50% + margin-left negative (value is half the width of the element)
4. Absolute element: left: 50% + Transform: translateX (-50%)

Vertical center

1. Inline elements: line-height equals height
2. Absolute element: top: 50%+margin-top negative (value is half of the height of the element)
3. Absolute element: Top: 50%+ Transform: translateY (-50%)
Absolute: +top, left, bottom, right=0+  margin:auto

Horizontal and vertical center

It is the above horizontal center + vertical center combined here I give a few common examples:

1. Absolute box placed in relative box:

top: 50%; left: 50%; transform: translate(-50%,-50%);



2. Know the width and height of the box

top: 50%; left: 50%;

Margin-left minus (half the width of the element); Margin-top negative value (value half the height of the element)



3. Absolute box placed in relative box with fixed width and height:

Top, left, bottom, right=0 + margin:auto



4. CSS3 Flexible Layout (Flex)

If you use CSS3’s Elastic layout (Flex), the problem becomes much easier. Using CSS3’s elastic layout is as simple as setting the parent element to the following properties

Display :flex // Flex layout

The align – items: center; // The element is horizontally centered

The justify – content: center; // The element is vertically centered



That’s it for this tutorial

The last

Finally, my name is Smooth, and I will write as many front-end tutorials as I can in 2022. I look forward to your attention

The latest publication plan isReactRelated teaching and my own brush test plan