内联元素的子元素在Chrome和Firefox中没有相同的反应

时间:2016-02-03 21:34:09

标签: html css google-chrome firefox compatibility

Chrome

  • 儿童的宽度相当于最后一行的内容。
  • 儿童的位置位于内容框的底部。

火狐

  • 儿童的宽度相当于内容框。
  • 儿童的位置位于第一行的底部。

结果
{{3}}



a {
  display: inline;
  color: black;
  position: relative;
  text-decoration: none;
}

a:after {
  background: #000;
  bottom: -3px;
  content: '';
  display: block;
  height: 3px;
  left: 0;
  position: absolute;
  width: 100%;
}

<a href="#">Very Long string that <br> break</a>
&#13;
&#13;
&#13;

任何人都知道为什么以及如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

根据CSS 2.1 Visual formatting model(同一模型适用于CSS 3),在内联上下文中呈现的元素将每行呈现为一个单独的逻辑块,称为行框

Firefox根据第一个行框的位置和尺寸(根据包含块的大小as calculated and defined in the specification)应用相对定位,这就是您遇到此行为的原因。

快速简便的解决方案是将父标记的显示模型指定为inline-block

尽管如此,规范并不清楚哪种行为是正确的(然而逻辑选择是Chrome的行为)。

Mozilla目前有针对此特定行为的错误:https://bugzilla.mozilla.org/show_bug.cgi?id=489100

答案 1 :(得分:0)

浏览器为inline元素呈现不同的换行符,只需使用border-bottom CSS属性即可实现所需的效果。

您尝试使用伪选择器作为边框,但它们的行为不同,它们使用总元素的盒子模型而不考虑换行符,因此建议采用另一种方法。

CSS :first-line方式

现在你不能使用纯CSS来定位元素的最后一行。你最好的纯CSS赌注是使用伪造的选择器::first-line,它要求父级是block / inline-block框。此外,::first-line仅接受有限数量的CSS属性。

<强>演示

a {
  display: inline-block;
  color: red;
  text-decoration: none;
}

a:first-line {
  color: black;
}
<a href="#">Very Long string that <br> break</a>

使用JS / jQuery获取最后一行

基本上使用javascript你可以获取字符串,分析它,拆分最后一行,将最后一行包裹在span内,然后将其追加。

查看示例代码:

var parText = $('a').text(); // get text of a
var parSplit = parText.split("\n"); // split text by \n
var lastLine = parSplit[parSplit.length-1]; // get last line
parText.replace(lastLine , ''); // replace last line with nothing
$('a').append('<span>'+lastLine+'</span>'); // append the last line with `<span>lastline</span>` and give it a style you need

来源:Mohamed-Yousef

简单的CSS范围

如果你可以修改HTML,这将是最简单的方法,基本上将最后一行(或<br>之后的文本)包裹在一个跨度内,这将获得你想要的样式。

<强>演示:

a {
  display: block;
  color: black;
  position: relative;
  text-decoration: none;
}

a span {
  border-bottom:3px solid #000;
}
<a href="#">Very Long string that <br> <span>break</span></a>

相关问题