An easy solution is to apply the float:left;
style to all links as previously suggested. However, using float may not be ideal for more complex layouts.
It's also a good idea to add semantic markup for clarity, such as wrapping the links in a <nav>
element. The only reason to have the links as siblings of the div might be for JavaScript functionality, but it can likely be optimized with additional surrounding markup.
You could explore using flexbox for a more flexible approach:
.container{
display:flex;
flex-direction: row;
justify-content: space-between;
border: 1px solid blue;
}
ul{
flex: 1 1 auto;
align-self: flex-start;
display:flex;
flex-direction: column;
padding: 0;
margin: 0;
}
li{
border: 1px solid red;
flex: 1 1 auto;
}
a {
background: tan;
}
div.main {
flex: 0 1 100px;
height: 200px;
background: green;
}
<div class="container">
<ul>
<li><a href="#1">Link 1</a></li>
<li><a href="#2">This is link 2.</a></li>
<li><a href="#3">3rd</a></li>
</ul>
<div class="main">lore ipsum</div>
</div>
To achieve this without using float and maintain flexibility, you may need to introduce some additional markup. While there may be exceptions in certain cases, there is no generic solution without extra markup. Using JavaScript to address this issue would likely not be practical.
The unnecessary nesting of li
elements in your case serves as a reminder to avoid directly positioning anchor tags within them. Wrapping anchor tags is generally recommended, as direct positioning with flexbox can lead to unexpected issues.
If div.container
represents the document's body
, you can simplify the structure further:
body{
display:flex;
flex-direction: row;
justify-content: space-between;
border: 1px solid blue;
}
nav{
flex: 1 1 auto;
align-self: flex-start;
display:flex;
flex-direction: column;
padding: 0;
margin: 0;
}
a {
background: tan;
}
div {
flex: 0 1 100px;
height: 200px;
background: green;
}
<nav>
<a href="#1">Link 1</a>
<a href="#2">This is link 2.</a>
<a href="#3">3rd</a>
</nav>
<div>lorem ipsum</div>