一、基本概念
在网页开发中,我们经常需要将某个元素固定在屏幕的中央位置,而这种情况下我们就需要使用到固定定位(fixed position)。 固定定位是一种相对于浏览器窗口固定位置的定位,即在任何情况下,该元素的位置都不会发生改变。在固定定位下,元素不会随滚动条的滚动而滚动。 实现Fixed居中,就是将固定定位的元素设置成整个页面的水平垂直居中。
二、实现方式
实现Fixed居中有很多不同的方式。下面我们就从以下几个方面来详细讲解。
三、方法一:使用Flexbox布局
使用Flexbox布局是实现Fixed居中最简单的方式之一。我们可以使用以下CSS代码:
.container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
justify-content: center;
align-items: center;
}
上面的CSS代码将父容器(.container)设置成固定定位,然后将其上、左坐标都设置为50%。接着使用transform
属性将其平移至中间。最后使用display
属性将其设置为Flex布局,然后使用justify-content
和align-items
属性将其水平和垂直居中。
四、方法二:使用绝对定位
使用绝对定位也是实现Fixed居中的方法之一。我们可以使用以下CSS代码:
.container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 50%;
height: 50%;
background-color: #ccc;
}
上面的CSS代码同样将父容器(.container)设置成固定定位,然后将其上、左坐标都设置为50%。接着使用transform
属性将其平移至中间。
然后,我们将待居中的元素(.box)设置为绝对定位,上下左右都设置为0。然后使用margin
属性将其水平垂直居中,并设置宽高比例。这样我们就可以实现Fixed居中。
五、方法三:使用Grid布局
如果你熟悉Grid布局,那么使用Grid布局也是实现Fixed居中的方法之一。我们可以使用以下CSS代码:
.container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: grid;
place-items: center;
}
上面的CSS代码将父容器(.container)设置成固定定位,然后将其上、左坐标都设置为50%。接着使用transform
属性将其平移至中间。最后使用display
属性将其设置为Grid布局,然后使用place-items
属性将其水平和垂直居中。
六、方法四:使用文本对齐
如果想要在Fixed定位下只居中文本,我们可以使用以下CSS代码:
.container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
上面的CSS代码同样将父容器(.container)设置成固定定位,然后将其上、左坐标都设置为50%。接着使用transform
属性将其平移至中间。最后使用text-align
属性将其文本内容水平居中。
七、方法五:不使用Flexbox、Grid、文本对齐
如果你不想使用Flexbox、Grid和文本对齐,我们还有其他的方式。我们可以使用以下CSS代码:
.container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 50%;
height: 50%;
}
.box {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 50%;
height: 50%;
background-color: #ccc;
}
上面的CSS代码将父容器(.container)的上下左右都设置为0,然后使用margin
属性将其水平垂直居中,并设置宽高比例。这样我们就可以实现Fixed居中。如果父容器(.container)和待居中的元素(.box)的宽高比例一致,那么我们还可以使用以下CSS代码:
.container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
height: 50%;
background-color: #ccc;
}
上面的CSS代码将待居中的元素(.box)的上下左右都设置为0,然后使用transform
属性将其水平垂直居中。这样我们就可以实现Fixed居中。