I would like to make my li spread evenly across the width of the page.
How can I do this with css?
I would like to make my li spread evenly across the width of the page.
How can I do this with css?
You can use the display: table property, for example:
ul.menu{
width:100%;
padding:0;
display: table;
}
ul.menu li {
background-color:gray;
display: table-cell;
}
ul.menu li a{
display:block;
padding:5px;
text-align:center;
}
<ul class="menu">
<li><a href="#">LINK</a></li>
<li><a href="#">LINK</a></li>
<li><a href="#">LINK</a></li>
<li><a href="#">LINK</a></li>
<li><a href="#">LINK</a></li>
</ul>
If you know the exact number of <li>
's then use the code below, setting the percentage to match the 100%:
<style>
li {
display: inline-block;
width: 20%;
float: left;
}
</style>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
You can use Flexbox . Most browsers have an already well-established implementation, according to Can I Use .
I'm assuming your list will be horizontal, meaning% s of% s will be side by side. The secret is to declare your <li>
, which is your container as <ul>
, and in display: flex
s set the <li>
property. This property defines the possibility of a flex item to grow, if necessary. By setting it to 1, all remaining space in the container will be evenly distributed among your children.
See:
$('button').on('click', function(){
$('ul').append('<li>Teste</li>');
});
ul{
margin:0;
padding: 0;
width: 100%;
display: flex;
}
li{
background-color: yellow;
border: 1px solid black;
padding: 10px;
list-style: none;
flex-grow: 1;
}
button{
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Adicionar LIs</button>
<ul>
<li>Teste</li>
<li>Teste</li>
</ul>
Obviously, this code should suit your needs.
body {
margin:0;
}
ul {
padding: 0;
width: 100%;
font-size: 0;
}
li {
box-sizing: border-box;
text-align: center;
font-size: 16px;
border: 1px solid;
width: 33.33%;
padding: 10px;
display: inline-block;
}
<ul>
<li>OLÁ</li>
<li>HELLO</li>
<li>HOLA</li>
</ul>
EXPLANATION:
font-size:0;
: this is so that there are no margins in the child elements that have as display inline-block
, our <li>
<li>
, this will give us the length of each relative to the parent element ... Which has the length of the window