html - 使用 CSS 在图像后添加空格和首字下沉

标签 html css pseudo-element

我认为有一种方法可以使用 :after 伪元素来做到这一点,但我不太明白。

这是针对 CMS 的,我无法编辑 div class=entry-text 之间的内容标签。

我有一个 div进入其中一个<p>被插入,有时带有 <a><img /></a>在文本之前,但有时只是文本。

我希望该文本位于图像下方(如果存在),并且我希望该文本具有首字下沉。

<div class="entry-text">
  <p>This is some text</p>
</div>

<div class="entry-text">
  <p><a href="#"><img src="myimage.jpg" class="entry-image" /></a>
  This is some text</p>
</div>

<style>
 div.entry-text > p::first-letter, div.entry-text > p > a::after::first-letter { 
     float: left;
     color: red;
     font-size: 300%;
     line-height: 30px;
     padding: 10px 5px 0 5px;
     content: "";
 }
 div.entry-text > p > a::after {
     margin-top: 15px;
     content: "";
 }
 </style>

最佳答案

::first-letter伪元素不适用于 inline 元素。它仅在父元素是 block 级元素时才有效。自 p是一个 block 级元素,当只有文本时它工作得很好。

如果文本之前有任何其他标记,例如 <a href>或者例如 <div> , ::first-letter不会针对第一个字母,请参阅 example我在说什么。

建议 1:span 包裹文本, 这是一个内联元素并设置它的 displayblock .

div.entry-text > p > span::first-letter {
  color: red;
  font-size: 300%;
  line-height: 30px;
  padding: 0 0 0 0;
  content: "";
}
span {
  display: block;
}
<div class="entry-text">
  <p>
    <span>This is some text</span>
  </p>
</div>

<div class="entry-text">
  <p>
    <a href="#">
      <img src="myimage.jpg" class="entry-image" />
    </a>
    <span>
        This is some text
    </span>
  </p>
</div>


建议 2:.entry-text 中与 img , 使用另一个 p标记文本。

div.entry-text > p::first-letter {
  color: red;
  font-size: 300%;
  line-height: 30px;
  padding: 10px 5px 0 5px;
  content: "";
}
div.entry-text > p > a::after {
  margin-top: 15px;
  content: "";
}
div.entry-text > p > a > img {
  position: relative;
}
<div class="entry-text">
  <p>This is some text</p>
</div>

<div class="entry-text">
  <p>
    <a href="#">
      <img src="myimage.jpg" class="entry-image" />
    </a>

    <p>
      This is some text
    </p>
  </p>
</div>

建议 3(不是最好的,但至少 ::first-letter 有效):将 <img>在文本之后使用 float:left;将其放在文本之前。

div.entry-text > p::first-letter { 
     color: red;
     font-size: 300%;
     line-height: 30px;
     padding: 10px 5px 0 5px;
     content: "";
 }
 div.entry-text > p > a::after {
     margin-top: 15px;
     content: "";
 }

div.entry-text > p > a > img {
  float:left; 
}
<div class="entry-text">
  <p>This is some text</p>
</div>

<div class="entry-text">
  <p>
    This is some text
    <a href="#">
      <img src="myimage.jpg" class="entry-image" />
    </a>
  </p>
</div>

关于html - 使用 CSS 在图像后添加空格和首字下沉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29906994/

相关文章:

jquery - 在 jquery 中纠正我

javascript - 将 id 作为参数传递

html - 垂直对齐 svg 内的图像

html - 不需要的垂直滚动条

html - IMG 下方宽度为 100% 的内容 Div 将无法在 IMG 下方正确显示

javascript - 在内容可编辑的 div 中选择文本,它是 jquery 可拖动的

jquery - 保持宽高比的全屏 div 中的图像

html - CSS数据属性换行符&伪元素内容值

html - Firefox 的 CSS 箭头渲染问题

css - apply::after 在同一个类的所有元素上