简体   繁体   中英

how to make the background color fill the entire element of a li tag

Hey so i have a horizontal nav bar, that i made using an li tag, and when i try and fill in the background of the "active" tag the background-color will only fill in just around the word and not the entire box `

 #menuBar ul { list-style: none; margin-top: 0px; } #menuBar ul li { float: left; width: 22%; font-size: 36pt; color: red; padding-top: 0px; border-style: solid; border-color: black; border-width: thin; text-align: center; margin-left: 0px; margin-right: 0px; } #content h1 { display: block; clear: both; } .active { background-color: red; color: yellow; } 
 <div id="menuBar"> <ul> <li class="home"><a class="active" href="#">Home</a></li> <li class="location"><a href="#">Location</a></li> <li class="history"><a href="#">History</a></li> <li class="culture"><a href="#">Culture</a></li> </ul> </div> 

Make the a a block element and the issue will be fixed:

 body { margin:0; } #menuBar ul { list-style: none; margin-top: 0px; } #menuBar ul li { float: left; width: 23%; font-size: 36pt; color: red; padding-top: 0px; border-style: solid; border-color: black; border-width: thin; text-align: center; margin-left: 0px; margin-right: 0px; } #menuBar ul li a { display:block; } #content h1 { display: block; clear: both; } .active { background-color: red; color: yellow; } 
 <div id="menuBar"> <ul> <li class="home"><a class="active" href="#">Home</a></li> <li class="location"><a href="#">Location</a></li> <li class="history"><a href="#">History</a></li> <li class="culture"><a href="#">Culture</a></li> </ul> </div> 

By the way i advise you to consider a better way to create your menu. Use flex instead of float:

 * { box-sizing: border-box; } body { margin: 0; } #menuBar ul { list-style: none; margin: 0; padding: 0; display: flex; } #menuBar ul li { flex: 1; font-size: 36pt; color: red; padding-top: 0px; border-style: solid; border-color: black; border-width: thin; text-align: center; margin: 0; } #menuBar ul li a { display: block; } .active { background-color: red; color: yellow; } 
 <div id="menuBar"> <ul> <li class="home"><a class="active" href="#">Home</a></li> <li class="location"><a href="#">Location</a></li> <li class="history"><a href="#">History</a></li> <li class="culture"><a href="#">Culture</a></li> </ul> </div> 

Your solution works already

I tried it with this simple html

<div id="menuBar">
<ul >
<li>foo</li>
<li>bar</li>
<li class="active">active</li>
<li>baam</li>
</ul>
</div>

Here: JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM