【问题标题】:Width of the element depending on the width of another element - WITHOUT JavaScript元素的宽度取决于另一个元素的宽度 - 没有 JavaScript
【发布时间】:2020-08-10 18:23:21
【问题描述】:

我需要.divider 元素的长度等于文本的长度(.topic 类)+ 2em,这样分隔符就比文本长一点。这是否可能仅使用 CSS(无 JS)?

这是代码(和JSFiddle):

<div class="divider"></div>
<div class="topic">
<div class="topic_symbols">@</div>
<div class="topic_text">THIS IS THE SAMPLE TEXT</div>
<div class="topic_symbols">@</div>
</div>
<div class="divider"></div>

.divider {
  border-bottom: 2px solid #fdb239;
  margin-left: 10%;
  margin-right: 10%;
}

.topic {
  display: flex;
  font-family: Tahoma, Geneva, sans-serif;
  justify-content: center;
  align-items: center;
  font-weight: 700;
  font-size: calc(0.8em + 2.3vw);
}

.topic_symbols {
  color: #ee290b;
}

.topic_text {
  text-align: center;
  color: #3cae3f;
  margin: 1% 1em 1% 1em;
}

【问题讨论】:

  • 按长度你是指width还是height
  • 宽度,凯西。 @Paulie_D 提供了绝妙的解决方案。

标签: html css variable-length


【解决方案1】:

不要使用 div 进行样式设置,而是使用 .topic_text div 的伪元素。

.topic_text:before,
.topic_text:after {
  content: "";
  border-bottom: 2px solid #fdb239;
  position: absolute;
  width: calc(100% + 2em); /* adjust as required */
  left: -1em;
}

.topic_text:before {
  top: -.25em;
  /* adjust as required */
}

.topic_text:after {
  bottom: -.25em;
}

.topic {
  display: flex;
  font-family: Tahoma, Geneva, sans-serif;
  justify-content: center;
  align-items: center;
  font-weight: 700;
  font-size: calc(0.8em + 2.3vw);
  margin-top: 1em;
}

.topic_symbols {
  color: #ee290b;
}

.topic_text {
  text-align: center;
  color: #3cae3f;
  position: relative;
}
<div class="topic">
  <div class="topic_symbols">@</div>
  <div class="topic_text">THIS IS THE SAMPLE TEXT</div>
  <div class="topic_symbols">@</div>
</div>

【讨论】:

  • 非常感谢您!我还不擅长伪元素,但您的回答是深入研究它们的良好起点。
  • 如果您不介意,请稍作说明:调整.topic_text:before, .topic_text:after 中的width(代码开头)会更改方向上橙色条的宽度只要。让它120%,你会明白我的意思。条形的宽度是否有可能均等地向两侧变化(即 120% 将在右侧增加 10%,在左侧增加 10%)?谢谢!
  • 线条的位置基于left 值,该值是额外宽度的一半(所以 2em 宽,向左调整 -1em...看到了吗?
  • 是的,我自己解决了——想写在这里,但你是第一个。 :-) 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-09-13
  • 2017-12-31
  • 2020-02-15
  • 2011-02-13
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 2018-10-15
相关资源
最近更新 更多