CSS float属性用于设置或返回元素的水平对齐方式。但是此属性允许元素仅在父实体的右侧或左侧浮动, 其余元素环绕在其周围。无法在CSS布局中浮动中心。因此, 我们可以使用position属性将元素居中。
示例1:本示例将元素的位置设置为恰好在屏幕中央。
<!DOCTYPE html>
<html>
<head>
<title>
Make float to center to element
</title>
<!-- Style to set element float
to center -->
<style>
.Center {
width:200px;
height:200px;
position: fixed;
background-color: blue;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>
</head>
<body>
<div class = "Center"></div>
</body>
</html>
输出如下:

例子:本示例将文本浮动元素的位置设置为恰好在屏幕中央。
<!DOCTYPE html>
<html>
<head>
<!-- Style to set text-element
to center -->
<style>
.center {
text-align-last: center;
border: 2px solid black;
}
</style>
</head>
<body>
<h2 style = "text-align:center">
Text is centered:
</h2>
<div class = "center">
<p>
<font color = "green">
lsbin A Computer
Science Portal for Geeks
</font>
</p>
</div>
</body>
</html>
输出如下:
