Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use CSS to implement centering

Shulou Source: shulou.com Published: 2022-06-01 10:44:25 09月18日 Update

This article mainly introduces how to use CSS to implement the center, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

CSS centering is often used in design, we often need to center when we use css to layout, sometimes a property can be done, and sometimes it takes some skill to be compatible with all browsers. There are many different ways to use css to achieve vertical centering of objects, but it is more difficult to choose the right one. For example, we all know that margin:0 auto; styles center elements horizontally, while margin: auto; cannot center vertically. The following is a concentrated introduction to some common methods of css centralization.

First of all, the level is in the middle, and the easiest way is, of course:

Margin:0 auto

Horizontal centering of text:

You can use the same setting of line-height as height:

Eg:

.div {

Width:200px

Height: 200px

Line-height: 200pxram * the key to vertical centering * /

Text-align:center

Font-size: 36px

Background-color: # ccc

}

Absolute positioning center

Parent container element: position: relative, child element: position:absolute

Eg:

.box {position:relative;width:200px;height:200px;background:#999;}

.content {

Width: 50%

Height: 50%

Overflow: auto

Margin: auto

Position: absolute

Top: 0; left: 0; bottom: 0; right: 0

Background:#C9F;}

The effect is as follows:

To learn these methods, it is actually very easy for css to be in the middle

! Note: height must be defined. It is recommended to add overflow: auto to prevent content overflow.

Flex in the middle

Introduce the method of horizontal and vertical centering of display:flex in CSS3.

Eg:

I am centered horizontally and vertically through flex!

.parent {

Display:flex

Align-items: center;/* is vertically centered * /

Justify-content: center;/* level is in the middle * /

Width:200px

Height:200px

Background-color:green

}

.children {

Background-color:blue

Color:#FFF

}

Thank you for reading this article carefully. I hope the article "how to use CSS to center" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Method level article element difference value key interest content method at the same time container object namely attribute layout common use suggestion skill effect Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker Shulou Information OPPO Reno MariaDB macOS