CSS响应中心部门

use*_*255 4 html css background center

我想将一些具有背景图像的div居中.这个div的响应有问题,因为如果我将宽度设置为80%,高度设置为80%,则bg图像不在中心.我尝试了一切,但图片不能只是站在中心,如果浏览器更小或更大,这是一个非常大的问题.

所以,如果你看看图片

挡在中心

我想让这个白色块响应.

我已经编写了一些css,但现在没有响应:

top: 20%;
left: 30%;
display: block;
position: absolute;
background: url(images/background.png) no-repeat;
background-size: 750px 417px;
width: 750px;
height: 417px;
Run Code Online (Sandbox Code Playgroud)

Fre*_*oux 10

我想在2年前做同样的事情,有解决方案:

因为您希望它具有响应性,所以您可以@media在CSS3中使用该功能.像这样:

@media (max-width: 480px) {
    #div {
        top: 50%; /* IMPORTANT */
        left: 50%; /* IMPORTANT */
        display: block;
        position: absolute;
        background: url(images/background.png) no-repeat center center;
        width: 750px;
        height: 417px;

        margin-top: -208.5px; /* HALF OF THE HEIGHT */
        margin-left: -375px; /* HALF OF THE WIDTH */
    }
}
Run Code Online (Sandbox Code Playgroud)

max-width您使用的是设备屏幕的最大宽度.您只需复制它并更改width, height, margin-left and margin-top图像即可.另外,你应该改变background标签!

它将图像置于页面中心.

你可以看到一个例子:CréationsMicroWeb - Carrières.即使您更改窗口侧,图像也完全居中.

您可以添加overflow: hidden;body使页面unscrollable当分辨率太低.像我一样.

编辑:JSFiddle


mon*_*ena 5

尝试使用自动边距并显示为表格:

.your-class {
  margin-left: auto;
  margin-right: auto;
  display: table;
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*ick 5

您可以使用CSS转换:

position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
Run Code Online (Sandbox Code Playgroud)