如何让背景覆盖一个单独的div?

How to make a background cover a separate div?(如何让背景覆盖一个单独的div?)

本文介绍了如何让背景覆盖一个单独的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个带有侧边菜单的网站.屏幕的 30% 是菜单,其余是内容.

I'm doing a site with side-menu. 30% of the screen is the menu and the rest is content.

div的内容,我用COVER方法放了一张背景图.我用了第一个例子:https://css-tricks.com/examples/FullPageBackgroundImage/css-1.php

The contents of the div, I put a background image using the COVER method. I used the first example: https://css-tricks.com/examples/FullPageBackgroundImage/css-1.php

但是,当图像占据整个背景时,此方法非常有效.在我的示例中,我希望相同的精确占据 70% 的宽度,吃掉"图像的角落.

However, this method works perfectly when the image occupies the entire background. As in my example, I want the same exact occupy 70% of the width, "eats" the image corners.

我该如何解决这个问题?

How can I fix this?

HTML:

<div id="esquerda" style="width: 30%; height: 500px">
 ....conteudo.....
</div>

<div id="direita" style="width: 70%; height: 500px">
   <img src="fundo.jpg" class="bg">

</div>

CSS:

.bg {
    min-height: 100%;
    min-width: 1024px;

    width: 100%;
    height: auto;   

    position: fixed;
    top: 0;
    float: right;
}


@media screen and (max-width: 1024px){
     .bg {
        left: 50%;
        margin-left: -512px; 
     }
}

推荐答案

使用 background-image 和 3 个不同元素的基本方法(以防止主要与 Safari 相关的 xBrowser 问题)
#bg 图层元素上将背景设置为 cover

Basic approach using background-image and 3 different elements (to prevent xBrowser issues related mostly to Safari)
setting the background to cover on the #bg layer element

*{ box-sizing: border-box;}
html, body{ height:100%; }
body{ position:static; margin:0; }

#bg{
  background: url('http://www.gettyimages.ca/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg') 50%;
  background-size: cover;
  position: fixed;
  top: 0; right: 0; bottom: 0;
  width: 70%;
}
#menu{
  position: fixed;
  bottom: 0; top: 0; left: 0;
  width: 30%;
  background: rgba( 0, 0, 255, 0.4 );
}
#page{
  position: relative;
  border: 10px dashed #000;
  margin-left: 30%;
  width: 70%;
  height: 2000px;
}

<div id="bg">BG</div>
<div id="menu">FIXED</div>
<div id="page">SCROLLABLE</div>

在该代码之上,您可以随意应用 CSS3 媒体查询.

on top of that code you can apply CSS3 media queries as you please.

注意最简单的"是使用单独的 #bg 元素,而是使用使用 background-attachment: fixed; 将 bg 图像直接设置为 #page 元素,但是如前所述,图像可能不会出现在 Safari 上,同时它的大小设置为封面.

Note that the "easiest" would be not to use the separate #bg element but instead to set the bg image directly to the #page element using background-attachment: fixed; but, as mentioned, the image might not appear on Safari in combination with it's size set to cover.

这篇关于如何让背景覆盖一个单独的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何让背景覆盖一个单独的div?

基础教程推荐