是否可以设置由“content”属性添加的图像的样式

时间:2015-08-25 12:58:17

标签: css

这是我的代码:

#my_div:before
{
  /* displaying the image */
  content: url("img path");
  /* centering the image */
  display: block;
  text-align: center;
  /* making the image responsive */
  max-width: 100%;
}
<div id="my_div"></div>

我正在尝试通过max-width:100%属性使图像响应,但它不起作用

我的问题:是否可以做这样的事情?

修改

问题不重复,我希望尺寸在屏幕上自动调整大小,而另一个问题为图像设置固定大小

2 个答案:

答案 0 :(得分:0)

试试这个:

#my_div:before
{
  /* displaying the image */
  content: url("img path");
  /* centering the image */
  display: block;
  text-align: center;
  /* making the image responsive */
  max-width: 100%;
  height: auto;
}

如果这不起作用,请尝试删除:before pseudo-element

#my_div
{
  /* displaying the image */
  content: url("img path");
  /* centering the image */
  display: block;
  text-align: center;
  /* making the image responsive */
  max-width: 100%;
  height: auto;
}

如果没有看到html的上下文,这是我能提供的最佳解决方案。我们需要更多信息才能更好地了解您的情况。

答案 1 :(得分:0)

我承认我并不完全确定你的影响是什么,但我认为这对你来说可能是更好的选择。

不要将图像放在content属性中......将该伪元素设为100%的div并使用背景图像。

为您提供几种选择。

&#13;
&#13;
.my_div {
  position: relative;
  height: 150px;
  border: 1px solid grey;
  width: 75%;
  margin: 1em auto;

}

.my_div:before {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  content: '';
  background-image: url(http://lorempixel.com/g/400/200/);
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
}

.cover:before {
  background-size: contain;
}
&#13;
<div class="my_div"></div>

<div class="my_div cover"></div>
&#13;
&#13;
&#13;

JSfiddle Demo