Home > Article > Web Front-end > Introduction to the method of using CSS to center floating elements
This article mainly introduces the method of using CSS to center floating elements. It is the basic knowledge for introductory learning of CSS. Friends in need can refer to it
Method 1
Set the floating mode of the container to absolute positioning
Then determine the width and height of the container, such as the layer with a width of 500 and a height of 300
Then set the margins of the layer
p{ width:500px; height:300px; margin:-150px 0 0 -250px; position:absolute; left:50%; top:50%; background-color:#000; }
Method 2
The parent element and the child element float to the left at the same time, then the parent element moves 50% relative to the left, and then the child element moves 50% relative to the right, or the child element moves relative to the left - 50% is fine.
<!DOCTYPE html><html><head> <title>Demo</title> <meta charset="utf-8"/> <style type="text/css"> .p{ position:relative; left:50%; float:left; } .c{ position:relative; float:left; rightright:50%; } </style></head><body> <p class="p"> <h1 class="c">Test Float Element Center</h1> </p> </body> </html>
The above is the detailed content of Introduction to the method of using CSS to center floating elements. For more information, please follow other related articles on the PHP Chinese website!