I'm encountering a minor issue with displaying a ul element as I am just starting to learn CSS.
My goal is to set the width of my ul
to match the widest listitem
it contains.
Below is the HTML code I have used:
<div id="sidebar">
<ul id="sidebarSelector">
<li><a href="#">Social Spot</a></li>
<li><a href="#" class="selectedSidebarItem">Profile</a></li>
<li><a href="#">Latest</a></li>
<li><a href="#">Settings</a></li>
</ul>
</div>
This is the corresponding CSS:
#sidebar
{
float:left;
width:20%;
}
#sidebar > ul#sidebarSelector
{
margin-top:100px;
list-style:none;
text-align:right;
/*overflow:auto;*/
}
#sidebar > ul#sidebarSelector > li > a
{
display:block;
padding:5px 10px;
font-family: "Open Sans Bold", Helvetica, Arial, sans-serif;
font-size:16px;
font-weight:500;
text-decoration:none;
text-transform:uppercase;
color:#000000;
}
.selectedSidebarItem
{
background-color:#0094ff;
font-weight:700;
border-radius: 3px; /*for rounded edges*/
box-shadow: 0px 0px 15px #0094ff; /*for glowing*/
}
I attempted to use a jQuery function mentioned below but did not achieve the desired result.
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').appendTo(document.body);
var htmlText = text || this.val() || this.text();
htmlText = $.fn.textWidth.fakeEl.text(htmlText).html(); //encode to Html
htmlText = htmlText.replace(/\s/g, " "); //replace trailing and leading spaces
$.fn.textWidth.fakeEl.html(htmlText).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};
var maxWidth = 0;
$('a').each(function(i){
if($(this).textWidth($(this).text, $(this).css('font')) > maxWidth)
maxWidth = $(this).textWidth($(this).text, $(this).css('font'));
});
$('#sidebarSelector').width(maxWidth);
The current output based on the HTML and CSS provided can be seen in the image below:
Desired output: