CSS子元素宽度的问题
以下demo,有一个父元素parent,包含了两个子元素child。首先父元素指定了宽度300px,两个子元素宽度为100%,实际效果是子元素平均分割了父元素的宽度,即子元素宽度变成了50%。
而我希望是第1个子元素的宽度就是父元素的100%,第2个子元素溢出到右侧。应该怎么实现?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
.parent {
border: black 2px solid;
height: 200px;
width: 300px;
display: flex;
}
.parent div:first-child {
background-color: brown;
}
.parent div:last-child {
background-color: darkturquoise;
}
.child {
height: 100%;
width: 100%;
}
</style>
<div class="parent">
<div class="child">子级1</div>
<div class="child">子级2</div>
</div>
</body>
</html>
两个子元素 要是都有宽话 直接都写上宽,父元素不写宽 dkdk135 发表于 2021-12-29 16:53
两个子元素 要是都有宽话 直接都写上宽,父元素不写宽
不能写死宽度。
实际应用中,父元素的宽度也是不确定的。
用定位吧,兄弟
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
.parent {
border: black 2px solid;
height: 200px;
width: 300px;
display: flex;
}
.parent div:first-child {
background-color: brown;
}
.parent div:last-child {
background-color: darkturquoise;
}
.child {
flex-shrink: 0;
height: 100%;
width: 100%;
}
</style>
<div class="parent">
<div class="child">子级1</div>
<div class="child">子级2</div>
</div>
</body>
</html> 定位?
这样?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
.parent {
border: black 2px solid;
height: 200px;
width: 300px;
display: flex;
position: relative;
}
.parent div:first-child {
background-color: brown;
}
.parent div:last-child {
background-color: darkturquoise;
position: absolute;
left: 100%;
}
.child {
height: 100%;
width: 100%;
}
</style>
<div class="parent">
<div class="child">子级1</div>
<div class="child">子级2</div>
</div>
</body>
</html> joker3 发表于 2021-12-29 17:15
Document
靠谱,通过flex-shrink不给压缩。 flex-wrap <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
.parent {
border: black 2px solid;
height: 200px;
width: 300px;
display: flex;
}
.parent div:first-child {
background-color: brown;
}
.parent div:last-child {
background-color: darkturquoise;
}
.child {
height: 100%;
width: 100%;
flex-shrink: 0;
}
</style>
<div class="parent">
<div class="child">子级1</div>
<div class="child">子级2</div>
</div>
</body>
</html> 你给css的.child里面加一个flex-shrink: 0;浏览器默认给你压缩了。
页:
[1]
2