How to center multiple buttons horizontally to the display size?
css, html, javascript, jquery
Solution
You can handle it using `CSS`, using `text-align: center` property.
Add it like here.
.tabs {
height: 34px;
padding-top: 1px;
padding-bottom: 0px;
background-color: #000;
text-align: center;
}
Check this JSFiddle
Problem
I'm having some difficulty centering some divs containing images inside a div. I am hoping to add buttons to HTML and have jQuery automatically center them but I can't get it quite right. I have a fiddle set up here: http://jsfiddle.net/uucp/m3UmA/ My original plan was to take the size of the container (named "tabs") and divide by the # of buttons (the number of "tab" classes on the page) then set the width of each tab div to that value. I must be missing some elementary: default padding or margins? Confused, baffled, etc, any help would be appreciated. HTML: ``` <div id="tabs" class="tabs"> <div id="tab_chat" class="tab"> <img class="tab_button" id="tab_chat_img" src="http://hanford.org/users/uucp/jsfiddle/daychat.png"> </div> <div id="tab_users" class="tab"> <img src="http://hanford.org/users/uucp/jsfiddle/dayusers.png"> </div> <div id="tab_images" class="tab"> <img src="http://hanford.org/users/uucp/jsfiddle/dayimages.png"> </div> <div id="tab_night" class="tab"> <img src="http://hanford.org/users/uucp/jsfiddle/daynight.png"> </div> <div id="tab_refresh" class="tab"> <img src="http://hanford.org/users/uucp/jsfiddle/dayrefresh.png"> </div> <div id="tab_settings" class="tab"> <img src="http://hanford.org/users/uucp/jsfiddle/daysettings.png"> </div> </div> <p> <div id="console"></div> </p> ``` CSS: ``` .tabs { height: 34px; padding-top: 1px; padding-bottom: 0px; background-color: #000; } .tab { text-align: center; border: 0; display: inline-block; color: #fff; } div.tab_button { border: 0; width: 32px; height: 32px; } ``` JavaScript: ``` var tabCount = $(".tab").size(); var offset = 24; var tabWidth = Math.floor(($("#tabs").width() / tabCount)); $('.tab').each( function (i, tab) { $(tab).css("width", tabWidth + "px"); $("#console").append("tabCount=" + tabCount + " tabWidth=" + tabWidth + " tabs.width=" + $("#tabs").width() + "<br/>"); }); ``` Thank you.