如何在div背景上应用最小宽度?

时间:2016-10-27 17:34:20

标签: html css

<div style="background: url(http://netdna.webdesignerdepot.com/uploads/2013/11/picjumbo.com_IMG_3130.jpg) no-repeat center center;
    background-size: 100%; min-width: 700px; height: 100%; width: auto;">

  <p>
    I DO NOT WANT THIS CONTENT TO BE AFFECTED BY THE MIN-WIDTH. I just want the background to take on min-width. I hope that makes sense.</p>

</div>

这是我的小提琴:

https://jsfiddle.net/y0bdLgzL/2/

  • 我在线应用样式,因为对于这个特定项目,我需要能够基于数据库动态生成背景图像。
  • 我试图让背景采用最小宽度属性,而不是内容/文本。

如何正确安排div和类以帮助实现这一目标的任何帮助都将非常有用。

2 个答案:

答案 0 :(得分:1)

您可以使用::before伪元素来实现此结果,如下所示:

<div class="wrapper">
    <p>
        Lorem ipsum solor dit amet
    </p>
</div>

.wrapper { height: 100%; position: relative; width: auto; }
.wrapper::before { background: url('img/bg.png') 0 0/100% 100% cover; content: ''; min-width: 700px; left: 0; position: absolute; top: 0; }

调整.wrapper::before的大小,后面会跟着!

答案 1 :(得分:0)

由于你无法给出背景图像的最小宽度,你可以使用伪元素,就像这样。

Updated fiddle

.bkg {
  position: relative;
  height: 100%;
  width: auto;
}
.bkg::before {
  content: '';
  position: absolute;
  background: url(http://netdna.webdesignerdepot.com/uploads/2013/11/picjumbo.com_IMG_3130.jpg) no-repeat center center;
  left: 0;
  top: 0;
  width: 100%;
  min-width: 700px;
  height: 100%;
}
.bkg p {
  position: relative;
}
  <div class="bkg">

    <p>
      I DO NOT WANT THIS CONTENT TO BE AFFECTED BY THE MIN-WIDTH. I just want the background to take on min-width, not the content. I hope that makes sense.</p>

  </div>