Div开始时的图标/图像

时间:2019-06-12 13:09:58

标签: html css

我正在尝试在这样居中的div文本的开头放置一个17x17 px png图像:

   [img] text text
text text text text text
text text text text text
<div style="text-align: center; height: 45px; width: 200px">
        <img src="icon" />
        <div>
            Some longer text.
        </div>
</div>

“难点”:文本必须保留在div中,并且div只能包含文本。而且div也必须保持div,或者至少必须具有height属性。

我在css上尝试了很多,但始终无法解决我的需要。谢谢!

编辑:div中的文本不一定很长。也可以只是一个字。

2 个答案:

答案 0 :(得分:0)

您可以使用伪元素::before在div中显示图像:

#myDiv::before {
    content: url('image.png');
}

Here's a working fiddle

答案 1 :(得分:0)

我认为您需要遵循以下原则:

  • 将图标和标题居中的标题
  • 包含其余文本的部分

这可以轻松地通过flex box的几行来完成。遵循以下原则:

 <header class="center-text">
  <img src="https://forum.starmen.net/include/images/smilies/cool3.png" /> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae, eum, debitis earum dignissimos nobis quos, nulla voluptates temporibus voluptatum ad repellat, nam dicta. Recusandae
  ea quasi eligendi, nulla labore molestias.
</header>
<section>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis sint voluptatem, id fuga adipisci dolor ut deleniti, est provident quis expedita nostrum ipsum sunt maiores obcaecati esse repellat tempore sed. Lorem ipsum dolor sit amet, consectetur
  adipisicing elit. Perspiciatis sint voluptatem, id fuga adipisci dolor ut deleniti, est provident quis expedita nostrum ipsum sunt maiores obcaecati esse repellat tempore sed. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis sint
  voluptatem, id fuga adipisci dolor ut deleniti, est provident quis expedita nostrum ipsum sunt maiores obcaecati esse repellat tempore sed. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis sint voluptatem, id fuga adipisci dolor
  ut deleniti, est provident quis expedita nostrum ipsum sunt maiores obcaecati esse repellat tempore sed. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis sint voluptatem, id fuga adipisci dolor ut deleniti, est provident quis expedita
  nostrum ipsum sunt maiores obcaecati esse repellat tempore sed.
</section>

<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.center-text {
  display: flex;
  justify-content: center;
}
</style>