html flex布局使用笔记及问题

本文探讨了在CSS Flex布局中,如何让子元素根据其内容自适应高度。通过设置`align-items`属性为`flex-start`、`flex-end`、`center`、`baseline`或`stretch`,可以控制子元素在交叉轴上的对齐方式。当使用`align-items: stretch`时,子元素会填满整个容器的高度,但若要避免垂直居中,可以调整为`align-items: flex-start`,并结合`margin`和`padding`实现所需效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

设置flex布局后,子元素高度占满,不能根据子元素的子元素去自适应高度。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<link rel="stylesheet" type="text/css" href="css/reset.css"/>
		<title></title>
		<style>
			body{
			    min-height: 100vh;
				background-color: #9b59b6;
				background-image: url("https://source.unsplash.com/nDqA4d5NL0k/2000x2000");
				display: flex;
				justify-content: center;
			}			
			#bands {
				background-color: rgba(255,255,255,1);
				list-style: inside square;
				width: 31.25rem;
				background: wheat;
				margin: auto;
			}			
		</style>
	</head>
	<body>
		<ul id="bands">
			<li>sdfdsfsd</li>
			<li>sdfdsfsd</li>
		</ul>
	</body>
</html>

解决方式:给子元素加 margin: auto;
用了这种方式子元素会垂直方向居中

如果你不想居中

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<link rel="stylesheet" type="text/css" href="css/reset.css"/>
		<title></title>
		<style>
			body{
			    min-height: 100vh;
				background-color: #9b59b6;
		 		background-image: url("https://source.unsplash.com/nDqA4d5NL0k/2000x2000"); 
				display: flex;
				justify-content: center;
				align-items: flex-start;
			}			
			#bands {
				background-color: rgba(255,255,255,1);
				list-style: inside square;
				width: 31.25rem;
				background: white;
				box-shadow: 0 0 0.75rem 0.1875rem rgba(0,0,0,0.3);
				margin-top: 1.25rem;								
			}
			#bands li{
				border-bottom: 0.0625rem solid rgba(0,0,0,0.3);
				font-size: 1.3rem;
				padding: 0.625rem;
			}		
				
		</style>
	</head>
	<body>
		<ul id="bands">
			<li>sdfdsfsd</li>
			<li>sdfdsfsd</li>
		</ul>
		<script>
			const bands = ['The Plot in You', 'The Devil Wears Prada',
			 'Pierce the Veil', 'Norma Jean', 'The Bled', 'Say Anything',
			  'The Midway State', 'We Came as Romans', 'Counterparts',
			   'Oh, Sleeper', 'A Skylit Drive', 'Anywhere But Here', 'An Old Dog'];
			
		</script>
	</body>
</html>

解决方式
在使用了flex的父布局中使用 align-items: flex-start | flex-end | center | baseline | stretch;

flex-start:交叉轴的起点对齐。
flex-end:交叉轴的终点对齐。
center:交叉轴的中点对齐。
baseline: 项目的第一行文字的基线对齐。
stretch(默认值):如果项目未设置高度或设为auto,将占满整个容器的高度。
在配合margin和padding使用就行了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值