div中的图像:之后或:之前?

时间:2016-10-17 16:06:47

标签: html css

我正在尝试在div的右边有一个背景图像,而不是覆盖整个div。

现在它就像这样(div1是背景色):

<div id="div1">
    <div id="image"></div>
    Text
</div>

CSS:

.div1 {
    background: #324458;
    color: #FFF;
    font-size: 0.9em;
    font-weight: bold;
    padding: 10px;
    width: 100%;
    position: relative;
    border-radius:4px;
    height:40px;
    clear:both;
    overflow: hidden;
}

.image {
    background: url("url here");
    background-position: center center;
    background-size: cover;
    opacity: 0.3;
    height: 39px;
    margin: -10px;
    width: 300px;
    position:absolute;
    right: 10px;
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
    z-index: 0;
}

但是可以将图像显示在其中而不将其作为div1中的div吗?比如使用:after:before或其他内容?我只希望div image显示在div1的右边,并且是X宽度。

3 个答案:

答案 0 :(得分:4)

要在像@ ::和::之前的伪元素上显示背景图像,然后才应在其上加上content: '';

我已修复(您尝试使用类选择器定位ID)并在this fiddle上添加了上述背景图像。但它是这样的:

&#13;
&#13;
.div1 {
  background: #324458;
  color: #FFF;
  font-size: 0.9em;
  font-weight: bold;
  padding: 10px;
  width: 100%;
  position: relative;
  border-radius: 4px;
  height: 40px;
  clear: both;
  overflow: hidden;
}

.div1::after {
  content: '';
  background: url("https://unsplash.it/200/300");
  background-position: center center;
  background-size: cover;
  opacity: 0.3;
  height: 39px;
  margin: -10px;
  width: 300px;
  position: absolute;
  right: 10px;
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
  z-index: 0;
}
&#13;
<div class="div1">
  Text
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

有几种方法可以将图像放在div的右侧。您应该考虑使用图像标记显示图像,如下所示:

另外,在你的html中你定义了id,然后在css中你需要使用#而不是.。查看Difference between id and class in CSS and when to use it

一种方法:

<强> HTML:

<div id="div1">content</div>
<img id="image" src="url"/>

<强> CSS:

#div1 {
   display:inline-block;
   float:left;
}

#img {
   float:left;
}

默认情况下,div容器会一直拉伸它们的宽度,以匹配其父容器宽度的100%。设置&#39;显示:内联块&#39;将包装其内容并允许将不同的容器(包括图像)堆叠到两侧。

答案 2 :(得分:0)

这是对:before和:after的测试,您可以在每个HTML元素之前和之后放置文本或图像。

p.test:before {
    padding-right: 5px;
    content: url(/pix/logo_ppk.gif);
}
p.test:after {
    font-style: italic;
    content: " and some text after.";
}