Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right align and left align ul li elements in horizontal navigation bar

Tags:

css

I am coding a horizontal navigation bar for my site. The html is as follows:

        <nav>
            <ul>
                <li class="special_text"><a href="#">Hello1</a></li>
                <li><a href="#">Hello2</a></li>
                <li><a href="#">Hello3</a></li>
            </ul>
        </nav>

The css is as follows:

* {
    margin: 0;
    padding: 0;
}

body {
    background-color: white;
    margin: 15px auto;
    border: 1px solid black;
}

header {

}

ul {
    list-style: none;
    padding: 1em 0;
    border-bottom: 2px solid #61f231;
    border-top: 2px solid #61f231;
}

li {
    display: inline;
    padding: 0 1.5em;
    border-left: 2px solid #61f231;
}

li.special_text {
    font-size: 200%;
    font-weight: bold;
    color: black;
    font-family: "Arial Black";
}

li.special_text a {
    text-decoration: none;
}

I would like to have some <li> elements aligned left while others align right. When I try to float the ones that I want left or right there is a problem with the vertical alignment (the elements are no longer vertically aligned within the <ul> element.

Part of the problem arises from the fact that the first <li> element uses a different size font.

Any suggestions?

Thank you

like image 668
theyuv Avatar asked Oct 16 '14 17:10

theyuv


People also ask

How do I align ul items to the right?

To make a right-aligned version of the list, only three changes need to occur. First, set the "UL" "text-align" to "right". Second, change the left "background-position" from "0" to "100%" - which makes the image align up with the right edge. And finally change "padding-left" to "padding-right".

How do you right align Li in HTML?

li. right{ text-align: right;} should work, but maybe it is canceled by previous css ? Do you want to keep the other elements centered? Please provide working example.


1 Answers

All you need to do is wrap what you want in divs and float them left and right:

<nav>
        <ul><div class="floatleft">
                <li class="special_text"><a href="#">Hello1</a></li>
            </div>
            <div class="floatright">
                <li><a href="#">Hello2</a></li>
                <li><a href="#">Hello3</a></li>
            </div>
        </ul>
</nav>

and add to your css:

.floatleft {
    float:left;
}
.floatright {
    float:right;
}

To fix the issue with vertical aligning, you need to mess around with line-height with the affected li elements

Check out the fiddle

like image 133
starvator Avatar answered Oct 04 '22 00:10

starvator