這個問題在這里已經有了答案:
![如何在文本更改時保持 div 寬度為 50%?[復制]](https://img.uj5u.com/2021/12/30/b8df69823be44840a1e9834d1a90645e.png)
我有一個固定寬度的容器等于200px:
.container {
display: block;
width: 200px;
}
.text1 {
background-color: red;
width: 50%;
display: inline;
}
.text2 {
background-color: blue;
width: 50%;
display: inline;
}
<div class='container'>
<div class='text1'>Text1</div>
<div class='text2'>Text2</div>
</div>
div即使文本發生變化,我如何保持 50% 的子寬度?鏈接到JSFiddle:
uj5u.com熱心網友回復:
你可以在這里使用CSS Flexbox:
.container {
display: flex;
width: 200px;
}
.text1 {
background-color: red;
width: 50%;
}
.text2 {
background-color: blue;
width: 50%;
}
<div class='container'>
<div class='text1'>Text1</div>
<div class='text2'>Text2</div>
</div>
uj5u.com熱心網友回復:
CSS 解決方案
inline 元素僅消耗其內容指定的寬度。
去display: block;用float: left;或display: flex實施。
display: block 執行
.container {
display: block;
width: 200px;
}
.text {
width: 50%;
display: block;
float: left;
}
.text1 {
background-color: red;
}
.text2 {
background-color: blue;
}
<div class='container'>
<div class='text text1'>1</div>
<div class='text text2'>Text2</div>
</div>
display: flex 執行
在flex布局的情況下,不需要為子元素指定寬度。只需將flex-grow: 1或添加flex: 1到子元素。
.container {
display: flex;
width: 200px;
}
.text {
flex: 1;
}
.text1 {
background-color: red;
}
.text2 {
background-color: blue;
}
<div class='container'>
<div class='text text1'>1</div>
<div class='text text2'>Text2</div>
</div>
uj5u.com熱心網友回復:
使用彈性
.container {
display: flex;
width: 200px;
}
.text1 {
background-color: red;
width: 50%;
display: inline;
}
.text2 {
background-color: blue;
width: 50%;
display: inline;
}
<div class='container'>
<div class='text1'>Text1</div>
<div class='text2'>Text2</div>
</div>
uj5u.com熱心網友回復:
盡管 flexbox 應該可以作業,正如其他回應給出的那樣,但您也可以使用columns來做到這一點。
只需將.container上的column-count指定為 2 列,并將.text1和.text2上的column-width設定為 50% 。
這是它:
.container {
display: block;
width: 200px;
column-count: 2;
}
.text1 {
background-color: red;
column-width: 50%;
}
.text2 {
background-color: blue;
column-width: 50%;
}
<div class='container'>
<div class='text1'>1</div>
<div class='text2'>Text2</div>
</div>
這是JSFiddle。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/397288.html
上一篇:重用Javascript函式?
