[英]div or p tag inside of flex box wrapping
有没有办法让名为 Title 的 logo 文本 div 标签占据父 flexbox 内的内容空间,而不是包装。
我不想将只是一个 div 的 Title 设置为 100% 或使用 white-space:nowrap。 我只是希望它像一个 div 一样填充其内容空间,并且仅在需要时才进行包装。
还有为什么当另一个元素设置为 100% 时会发生这种情况。 就像下面的代码片段。
const styled = window.styled; const Header = styled.div ` width: 100%; display: flex; border: 1px solid gray; align-items: center; width: 100%; min-height: 50px; padding: 10px 10px 10px 30px; background-color: #147189; color: white; `; const Title = styled.div ` `; const TestDiv = styled.div ` width: 100%; border: 1px solid red; `; const App = () => { return ( <div> <Header > <Title > Logo Text </Title> <TestDiv > hello </TestDiv> </Header> </div> ); } ReactDOM.render(<App/>, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <script src="//unpkg.com/styled-components@4.0.1/dist/styled-components.min.js"></script> <div id="react"></div>
从TestDiv
定义中删除width: 100%
并添加margin-left: 2rem
(或您希望的任何值)以将其与其他 flex 项(即Title
组件)分开:
const TestDiv = styled.div `
margin-left: 2rem;
border: 1px solid red;
`;
或者,您可以将弹性项目的宽度设置为其父项( Header's)
宽度的百分比(总计 100%),如下所示:
const Title = styled.div `
width: 10%;
`;
const TestDiv = styled.div `
width: 90%;
border: 1px solid red;
`;
由于您不想使用whitespace: nowrap
,我想一种解决方法是根据标题文本参数化Title
div 的宽度。 我将Title
的width
设置为等于width + 3 ch
(另外 3 个仅用于填充并确保它不会换行)。 我想如果这可能会变得太长,你可以设置max-width: 25ch
或类似的东西。
希望这可以帮助。
const styled = window.styled; const Header = styled.div ` width: 100%; display: flex; border: 1px solid gray; align-items: center; width: 100%; min-height: 50px; padding: 10px 10px 10px 30px; background-color: #147189; color: white; `; const Title = styled.div ` `; const TestDiv = styled.div ` width: 100%; border: 1px solid red; `; const style = () => ({}); const setWidth = (width) => ({ width: `${width + 3}ch`, }); const App = () => { return ( <div> <Header > <Title style={ setWidth('Logo Text Whatever'.length) } > Logo Text Whatever </Title> <TestDiv > hello </TestDiv> </Header> </div> ); } ReactDOM.render(<App/>, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <script src="//unpkg.com/styled-components@4.0.1/dist/styled-components.min.js"></script> <div id="react"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.