【问题标题】:How to set percent width of a absolute component?如何设置绝对组件的百分比宽度?
【发布时间】:2022-11-08 21:12:44
【问题描述】:

我在relative 组件中声明了一个absolute 组件。当我尝试将宽度设置为width: 870px 时,它可以工作。

但是当我尝试将宽度设置为width: 80% 或使用 calc 作为width: calc(100% - 20px); 时,宽度不会改变。请指导我如何将百分比用于absolute 组件。

这是我的样式化组件代码:

export const StyledFooter = styled.div`
    width: 100%;
    position: relative;

`;

export const EnrollContainer = styled.section`
    position: absolute;
    width: calc(100% - 20px);
    max-width: 870px;
    padding: 80px 120px;
    top: 0%;
    left: 50%;
    transform: translate(-50%, -50%);
`;

这是 JSX 部分:

return(
  <StyledFooter>
       <EnrollContainer>Hello</EnrollContainer>
  </StyledFooter>
)

【问题讨论】:

  • 您是否设置了父级的width
  • 您只用css 标记了它,但CSS 不知道任何称为“组件”的东西。原生 HTML 也没有。所以我猜你在谈论来自那些(可怕的)客户端框架之一的东西......?但这不应该改变这样一个事实,这基本上是一个 HTML & CSS 问题 - 所以请提供正确的minimal reproducible example 问题,HTML 和 CSS。

标签: css


【解决方案1】:

您必须设置父级(相对一个)的宽度,否则它无法对未知宽度的父级执行百分比

#relative{
  position:relative;
  width:150px;
  border:2px solid black;
}

#absolute{
  position:absolute;
  width:50%;
  border:2px solid red;
}
<div id="relative">
  <div id="absolute"></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-24
    • 2012-10-03
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2012-04-05
    • 1970-01-01
    相关资源
    最近更新 更多