CSS插入框阴影与偏移量?

时间:2020-10-16 06:10:15

标签: css

我想要的结果是标题元素的下划线较粗,类似于左侧:

enter image description here

我正在使用下划线来处理内置CSS框阴影,但是我不知道如何从左侧偏移它,以使其与h2文本的开头不完全内联。

html {
  font-family: 'Roboto', sans-serif;
  font-size: 62.5%;
  // -ms-text-size-adjust: 100%;
  // -webkit-text-size-adjust: 100%;
}

body {
  word-wrap: break-word;
  overflow-x: hidden;
}

h2 {
  font-weight: bold;
  font-size: 2rem;
  line-height: 1.1;
}

h2 span {
  box-shadow: inset 0 -1.0rem 0 0 #88DEB2;
  padding-right: 1rem;
}
<h2><span>Incredible Pure Castile Soap</span></h2>

很高兴知道如何实现这一目标。

3 个答案:

答案 0 :(得分:4)

您可以使用伪元素::after::before,并使用向左或向右控制偏移/位置。代码在注释中说明。

html {
  font-family: 'Roboto', sans-serif;
  font-size: 62.5%;
  // -ms-text-size-adjust: 100%;
  // -webkit-text-size-adjust: 100%;
}

body {
  word-wrap: break-word;
  overflow-x: hidden;
}

h2 {
  font-weight: bold;
  font-size: 2rem;
  line-height: 1.1;
  width: max-content; /* Take the content width */
}

h2 span::after {
  content: " "; /* Let us 'activate' the pseudo element */
  display: block; 
  background: #88DEB2;
  height: 15px;
  position: relative; 
  top: -10px;
  left: 5px; /* Control the misalignment */
  z-index: -1; /* So that it appears underneath */
}
<h2><span>Incredible Pure Castile Soap</span></h2>

答案 1 :(得分:4)

您几乎不错,只需添加一个负数text-indent

html {
  font-family: 'Roboto', sans-serif;
  font-size: 62.5%;
}

body {
  word-wrap: break-word;
  overflow-x: hidden;
}

h2 {
  font-weight: bold;
  font-size: 2rem;
  line-height: 1.1;
  padding-left: 1rem;
}

h2 span {
  box-shadow: inset 0 -1.0rem 0 0 #88DEB2;
  display:inline-block; /* this is needed for the trick */
  text-indent: -1rem; /* here */
  padding-right: 1rem;
}
<h2><span>Incredible Pure Castile Soap</span></h2>

具有梯度的多线解决方案

html {
  font-family: 'Roboto', sans-serif;
  font-size: 62.5%;
}

body {
  word-wrap: break-word;
  overflow-x: hidden;
}

h2 {
  font-weight: bold;
  font-size: 2rem;
  line-height: 1.1;
  padding-left: 1rem;
}

h2 span {
  background:
    linear-gradient(#88DEB2,#88DEB2) 
    bottom right/calc(100% - 1rem) 1rem 
    no-repeat;
  padding-right: 1rem;
}
<h2><span>Incredible Pure Castile Soap</span></h2>

答案 2 :(得分:1)

您可以使用linear-gradient来伪造一个可以实现此目的的下划线(有关详细信息,请参见代码中的注释)

html {
  font-family: 'Roboto', sans-serif;
  font-size: 62.5%;
  // -ms-text-size-adjust: 100%;
  // -webkit-text-size-adjust: 100%;
}

body {
  word-wrap: break-word;
  overflow-x: hidden;
}

h2 {
  font-family: serif;
  font-weight: bold;
  font-size: 2rem;
  line-height: 1.1;
}

h2 span {
    background-image: linear-gradient(transparent 50%, #88DEB2 50%); /* makes a linear gradient */
    background-position: 5px 0; /* offsets it */
    background-repeat: no-repeat; /* stops it from repeating */
    padding-right: 5px; /* gives more space for the underline offset */
}
<h2><span>Incredible Pure Castile Soap</span></h2>