在data-bg中更改图像的CSS

时间:2016-03-12 10:30:57

标签: html css properties attributes

<div class="item" data-bg="images/demo-images/team_bg_1.jpg">

我想将data-bg属性中使用的图像定位到右下角。如何为data-bg属性应用CSS。

image的实际尺寸为900pxdiv的实际尺寸为100%

请帮助将图像放在右下角。

3 个答案:

答案 0 :(得分:3)

你不能用CSS“定位”一个“属性”。我猜你的意思是将data-bg中的图片作为.item div的背景。

首先,您需要将data-bg更改为style,以使图像显示为正确的CSS背景图像,如下所示:

style="background-image: url(images/demo-images/team_bg_1.jpg")"

在此之后,您可以使用CSS规则来定位背景并应用您想要的任何样式:

.item {
  background-repeat: no-repeat;
  background-position: right bottom;
  height: 300px;
  border: 1px solid red;
}
<div class="item" 
     style="background-image: url(https://placehold.it/900x200)">
</div>

jsFiddle演示:https://jsfiddle.net/

我不确定您为什么要使用data-bg,您是否有处理此数据属性的JavaScript代码?你的问题不够明确。

答案 1 :(得分:0)

要将背景图像定位到右下角,请使用以下css:

background-position: right bottom;

请注意,您无法在纯CSS中使用data-bg属性中的图片网址。有关详细信息,请参阅this link

答案 2 :(得分:0)

&#13;
&#13;
/*==============================
	BG BACKGROUND DATA BG
==============================*/
$('.bg-background-area').each(function() {
  "use strict";
  if ($(this).attr("data-bg")) {
    $(this).css({
      'background': 'url(' + $(this).data('bg') + ')',
      'background-position': 'center center',
      'background-repeat': 'no-repeat',
      'background-size': 'cover',
      'background-attachment': 'scroll'
    });
  }
});
&#13;
.bg-background-area {
  position: relative;
  margin: 40px 0;
  padding: 50px;
  min-height: 400px;
}

.bg-background-area:after {
  background-color: rgba(10, 0, 0, 0.8);
  content: '';
  display: block;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 0;
}

.bg-background-area p {
  color: #fff!important;
}

.bg-background-area h2 {
  color: #fff!important;
}

.bg-background-area h3 {
  color: #fff!important;
}

.bg-background-area .container {
  z-index: 1;
  position: relative;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section class="bg-background-area" data-bg="https://cdn.pixabay.com/photo/2018/05/12/00/32/coffee-3392168_960_720.jpg">
  <div class="container">
    <p>Test text ....... </p>
  </div>
</section>
&#13;
&#13;
&#13;