Home  >  Article  >  Web Front-end  >  Several commonly used CSS centering methods

Several commonly used CSS centering methods

PHPz
PHPzOriginal
2023-04-21 14:21:064089browse

The CSS centering method is one of the very basic technologies in web page production. Whether it is centered text or images, it can be achieved with simple CSS code. Below, we will introduce several commonly used CSS centering methods.

1. Center a div

To center a div, we can use the following CSS code:

div {
    width: 200px;
    height: 100px;
    margin: auto;
}

Among them, width and ## The #height attribute represents the width and height of the div. The margin:auto attribute can center the div horizontally and vertically.

2. Center an image

To center an image, we can use the following CSS code:

img {
    display: block;
    margin: auto;
}
Among them,

display:block attribute You can have the image wrap automatically so that it is centered. The margin:auto attribute can center the image horizontally and vertically.

3. Center a text box

To center a text box, we can use the following CSS code:

input[type=text] {
    display: block;
    margin: 0 auto;
}
Among them,

input[type=text ] represents the text box, and the display:block attribute can make the text box automatically wrap and center it. margin:0 autoThe attribute can center the text box horizontally and vertically by default.

4. Center the entire webpage

To center the entire webpage, we can use the following CSS code:

body {
    margin: 0 auto;
    text-align: center;
}
Among them,

margin:0 auto The attribute can center the web content horizontally, and the text-align:center attribute can center the web content vertically.

5. Center an absolutely positioned element

To center an absolutely positioned element, we can use the following CSS code:

div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
Among them,

position: The absolute attribute can position the element within the parent element, and the top:50% and left:50% attributes can center the element up, down, left, and right relative to the parent element. transform:translate(-50%,-50%)The attribute can move the position of the element to the upper left by half of its width and height, so that the element is perfectly centered.

To sum up, the above methods are commonly used CSS centering methods, but in actual applications, the corresponding centering method should be selected according to the specific situation.

The above is the detailed content of Several commonly used CSS centering methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn