简体   繁体   中英

get the total width of specified elements including there margin and padding

Ok i have this code.

<script>
$(document).ready(function(){

    var totalWidth = 0;

    $('.thewidgets').each(function(index) {
        totalWidth += parseInt($(this).width(), 10);
    });

    $('#marginwidgets').css({width: totalWidth});

});
</script>

the html

<div id="marginwidgets">
 <div class="thewidgets">
  the widgets 1
 </div>
 <div class="thewidgets">
  the widgets 2
 </div>
 <div class="thewidgets">
  the widgets 3
 </div>
</div>

and the css

#marginwidgets
{
margin: 0px auto;
overflow: auto;
max-width: 100%;
}
.thewidgets
{
width: 284px
padding: 5px;
margin-left: 10px;
}
.thewidgets:first-child
{
margin-left: 0px !important;
}

As you can see in the script, the routine is to get the total width of .thewidgets and then apply the total width of that into the #marginwidgets that should make perfect centralized of #marginwidgets.

but i want the total width of .thewidgets include there margin and there paddings and then apply it into the #marginwidgets but i dont know how to make it, could someone here figure it out how to do it please?

Use outerWidth instead of width, and pass true as an argument to include the margins:

$(this).outerWidth(true);

Also the dimension functions return Numbers as opposed to strings so parseInt isnt necessary though you might want to use Math.floor , Math.ceil or Math.round .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM