html flex布局使用笔记及问题

设置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使用就行了

猜你喜欢

转载自blog.csdn.net/LiuxXn/article/details/109727869