Do CSS rules exist for placing content within elements and positioning them?

烈酒焚心 提交于 2019-12-11 17:50:04

问题


Do CSS rules exist for placing content such as images or text within elements?

eg. say I have a div which can contain some info which is correct and some info which is wrong, can I have rules such as:

.correct {
  img: greenTick.jpg;
  text: "answer is wrong"
}

.wrong {
  img: redX.jpg;
  text: "answer is correct"
}

Is it possible to position them too?


回答1:


You can use pseudo elements (::before and ::after). Set the text using the content attribute, and the image as the background of the pseudo element or the div:

.correct::before {
  padding: 1em;
  background: url(https://picsum.photos/200/100);
  background-size: contain;
  color: white;
  content: "answer is correct"
}

.wrong::before {
  padding: 1em;
  background: url(https://picsum.photos/200/200);
  background-size: contain;
  color: white;
  content: "answer is wrong"
}
<div class="correct"></div>

<br><br>

<div class="wrong"></div>



回答2:


CSS background-image attribute would be the one that you need to use instead img. See below an example of how to do it with your both style classes:

.correct {
    background-image: url("greenTick.jpg");
}

.wrong {
    background-image: url("redX.jpg");
}


来源:https://stackoverflow.com/questions/52466693/do-css-rules-exist-for-placing-content-within-elements-and-positioning-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!