图片大小不改动,根据屏幕大小自动把图片居中显示

background属性

background-image: url(‘../img/1_1.jpg‘);   <!-- 背景图片路径 -->
background-repeat: no-repeat;   <!-- 背景图片是否重复显示 -->
background-position: center;   <!-- 若背景图片小于div,则居中显示 -->
background-attachment: fixed;   <!-- 背景图片固定,不随scroll拖动而变动 -->

居中显示

父容器

style="overflow-x:hidden"

子容器

position: absolute; left: 50%; top: 0%;     <!-- div向左移动屏幕宽度的50% -->
margin-left: -960px; margin-top: 0px;    <!-- div向左移动自身宽度的50% -->

子容器会居中显示,但右侧多余的东西要靠父容器的overflow-x:hidden隐藏。

如果要上下也居中显示,则postion的top也要设置为50%,margin-top设置为图片的一半.

html&css

<body style="overflow-x:hidden">

    <!--
    background-attachment: fixed;
     -->
    <div style="width: 1920px; height: 1420px;
     position: absolute; left: 50%; top: 0%;
     margin-left: -960px; margin-top: 0px;
     background-image: url(‘../img/1_1.jpg‘);
     background-repeat: no-repeat;
     background-position: center;">
    </div>
</body>

这样可以达到图片居中显示的效果。

相关推荐