【问题标题】:Prevent text from wrapping in an absolute positioned div防止文本在绝对定位的 div 中换行
【发布时间】:2020-06-26 15:03:43
【问题描述】:

我在 SO Preserve normal word wrapping inside absolutely positioned container 上发现了一个类似的问题。但是,接受的解决方案不会解决我的问题。我在divposition: absolute 中有一个divposition: relative。我希望我的文本出现在一行中,而不是每个单词都换行。

我的文件结构是这样的

  return (
    <TooltipContainer
      modifiers={modifiers}
      width={wrapperWidth}
      height={wrapperHeight}
    >
      <TooltipArrow modifiers={modifiers} />

      <TooltipLabel
        modifiers={modifiers}
      >
        {text}
      </TooltipLabel>
    </TooltipContainer>
  );

我的样式组件看起来像这样

const TooltipContainer = styled.div`
  position: absolute;
  z-index: 1;
  display: block;
  word-wrap: break-word;
  top: 0px;
  text-align: center;
  ${(props) =>
    props.modifiers.includes("right") ? `margin-left: ${props.width}px` : ""};
  ${(props) =>
    props.modifiers.includes("left") ? `right: ${props.width}px` : ""};

  font-family: ${secondaryFont};
  font-size: ${buttonTypeScale.small};
  ${applyStyleModifiers(TOOLTIP_CONTAINER_MODIFIERS)};
`;

const TooltipLabel = styled.div`
  background-color: ${basic[1100]};
  border-radius: 4px;
  color: ${basic[100]};
  padding: 0.5625rem 0.5625rem 0.4375rem 0.5625rem;
  visibility: hidden;
  text-align: center;
  position: relative;
  img {
    height: 0.75rem;
    width: 0.75rem;
    vertical-align: middle;
  }
  ${applyStyleModifiers(TOOLTIP_LABEL_MODIFIERS)};
`;

我的问题与上述问题的主要区别在于我使用margin-leftright 来调整容器的位置。我一直在测试不同的东西(设置不同的显示和位置),到目前为止,我发现唯一可行的方法是添加固定宽度或设置 width : 100% 两者都是不可取的,因为它们会改变填充。

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    您可以使用 CSS white-space: nowrap; 来防止单词换行。但请记住,这些词可能会以这种方式在 div 之外运行。如果您想查看 div 之外的单词,您可能需要使用 CSS overflow: visible;

    单词是环绕的,因为 div 不够大,无法容纳所有单词。您也可以尝试使用 CSS width: fit-content; 使 div 的宽度响应内部文本。

    我在您的第一个问题中看到您链接了JSFiddle。如果您有另一个 JSFiddle 可以查看,我可以告诉您我的意思。

    【讨论】:

    • 谢谢亚当! white-space: nowrap 正是我所需要的
    猜你喜欢
    • 2011-10-08
    • 1970-01-01
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    相关资源
    最近更新 更多