Grid-auto-flow:列无法以百分比值捕获儿童div宽度
我想使用CSS网格属性将行和某些跨度标签放在水平而灵活的情况下,就像以下捕获一样。
实际上,最简单的方法是将CSS Flex属性与GAP属性一起使用,但旧的iOS版本无法允许GAP属性。
因此,我使用了网格 - 自动流:列;
,但是由于此属性,子标签的宽度无法正常工作。
import styled from "styled-components";
export const Container = styled.div`
width: 375px;
display: grid;
/* grid-template-columns: repeat(5, 1fr); */
grid-auto-columns: auto;
place-content: center;
align-items: center;
grid-gap: 10px;
border: 1px solid blue;
`;
export const Flex = styled.div`
width: 375px;
display: flex;
align-items: center;
gap: 10px;
border: 1px solid blue;
`;
export const LineWithPercentage = styled.div`
width: 42%;
border-bottom: 1px solid black;
`;
export const LineWithPX = styled.div`
width: 164px;
border-bottom: 1px solid black;
`;
export const NumberWrapper = styled.div`
width: 22px;
height: 22px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 20px;
background-color: pink;
`;
export const Number = styled.span`
color: white;
`;
export default function App() {
return (
<>
<Container>
<NumberWrapper>
<Number>1</Number>
</NumberWrapper>
<NumberWrapper>
<Number>2</Number>
</NumberWrapper>
<span>Percentage</span>
<LineWithPercentage />
<NumberWrapper>
<Number>3</Number>
</NumberWrapper>
</Container>
<br />
<br />
<Flex>
<NumberWrapper>
<Number>1</Number>
</NumberWrapper>
<NumberWrapper>
<Number>2</Number>
</NumberWrapper>
<span>Px</span>
<LineWithPX />
<NumberWrapper>
<Number>3</Number>
</NumberWrapper>
</Flex>
</>
);
}
这个问题有好主意吗?
我还添加了CODESANDBOX链接。 https://codesandbox.io/nice-ptolemy/nice-ptolemy/nice-ptolemy/snice-ptolemymem -pbq4uh?file =/src/app.tsx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的状态正确,但是要获得与 flexbox 相同的结果,您需要:
容器样式
plot-content:center;
grid> grid-- grid--自动列:最小值;
grid-auto-flow:column;
之后,我们在 span line中遇到了其他问题,因为我们已经设置了
网格 - 自动列:最小式;
,所有Chidren元素都应与自己的绝对宽度叠在一起,但是 lineWithPercentage 样式具有相对宽度。为了解决此问题,我们使用calc()函数,其中我们从容器 样式 375px 0.42 (42%) 。You were was on the right way, but to get the same result as with Flexbox you need to:
Container style
place-content: center;
grid-auto-columns: min-content;
grid-auto-flow: column;
After that we get other problem with the span line, because we have set
grid-auto-columns: min-content;
and all chidren elements should stack in one line with their own absolute width, but LineWithPercentage style has relative width. To fix this, we use calc() function, where we take width 375px from the Container style of and multiply by 0.42 (42%).您需要使用网格板柱来定义想要多少列。
在这里,我们使用三列布局(网格 - 板柱:重复(3,1fr))并排对齐三件事。和文本一致性:中心将整个网格集中在容器内。
You need to use grid-template-columns to define how many columns you want.
Here, we are using three columns layout (grid-template-columns: repeat(3, 1fr)) to align three things side by side. And text-align: center to center the whole grid inside the container.