[英]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.