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.
img { display: block; margin: auto; }
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.
input[type=text] { display: block; margin: 0 auto; }
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.
body { margin: 0 auto; text-align: center; }
margin:0 auto The attribute can center the web content horizontally, and the
text-align:center attribute can center the web content vertically.
div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
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.
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!