Patrick Patrick - 26 days ago 7
CSS Question

Set height of <li> based of div height

hope you can help me.
I am trying to create a navigation with a variable amount of list elements. Now I want to automatically set the height of the list elements based on the height of the surrounding div element, and the number of list elements that are in the div. Is there a way to do so, or can I only do it the other way around, by simply not giving the div a height value, but rather give the list elements a fixed height?

Hope you can help me.

#nav ul{
margin: 0;
padding: 0;
list-style: none;
}

#nav{
margin-top: 30px;
width: 19%;
background-color: red;
float:left;
border-top: 1px solid black;
}

#nav ul li{
text-align: center;
width: 100%;
background-color: yellow;
height: 50px;
margin-top: 20px;
line-height: 50px;
border-bottom: 1px solid black;
border-left: 1px solid black;
transform: rotate(20deg);
}

Answer

You can use the below code,it will definitely work

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="change" style="height:200px;border:1px solid black">
<ul>
<li>HI</li>
<li>Hello</li>
<li>Bye</li>
<li>Byesdfsd</li>
<li>sdfsd</li>
<li>sdfsd</li>
</ul>
</div>
<script>
var height=document.getElementById("change").style.height;
height=height.replace("px","");
var lis=document.getElementsByTagName("li");
for(var i=0;i<lis.length;i++){
	lis[i].style.height=(parseInt(height))/(parseInt(lis.length))+"px";
	console.log("getting height "+lis[i].style.height);
}
</script>
</body>
</html>

  • So you can give the height of the div in a class or in the inline style,but you will have to change the code accordingly in the js part for fetching the height of the div.
  • I have got the li tags and then depending on their number i have divided the height of the enclosing div by the number of list tags