I have asp.net mvc4 project where I have bootstrap for markup and jquery for client side work.
<div class="row">
<div class="col-md-4 container" id="cont">
<div class="row overlay_container" id="overlayCont">
<div class="col-md-12 background" id="bg"></div>
<div class="col-md-12 text" id="txt">
<h1>This is a test!</h1>
This is also a test!
</div>
</div>
<div class="row">
<div class="col-md-12">
<img src="~/Content/Images/5.jpg" id="porfolioImage" />
</div>
</div>
</div>
var wdth = $("#porfolioImage").width();
alert(wdth);
var hgth = $("#porfolioImage").height();
alert(hgth);
$("#overlayCont").width(wdth).height(hgth);
$("#bg").width(wdth).height(hgth);
When hit alert it return wdth = 382 and hgth = 382, but after replace elements I have the following line
[<div class="col-md-12 background" id="bg" style="width: 412px; height: 382px;"></div>]
And I dont know why it insert 412 instead of 382. But I need 382. Any ideas where is my mistake?
$("#bg").width(wdth).height(hgth);
bg width doesn't include padding
col-md-12 has a padding-left: 15px & padding-right: 15px.
Your img width is 382px + 15px + 15px = 412px
I think the problem is because bootstrap or you set in css box-sizing
, like:
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
with this setting .width()
set the width of the element + padding and borders size.
To prevent this behavior without change CSS, i think you simply use .css()
instead of .width()
and .heigth()
, so this:
$("#overlayCont").width(wdth).height(hgth);
$("#bg").width(wdth).height(hgth);
change in:
$("#overlayCont").css({height:hgth, width:wdth});
$("#bg").css({height:hgth, width:wdth});
or, min version:
$("#overlayCont,#bg").css({height:hgth, width:wdth});
.css("width")
, .css("width",number)
return and get the css style (ignore padding, border and, box-sizing setting)
.width()
has a particular behavior dipends to css settings see http://api.jquery.com/width/ for more information.
or the console in my jsfiddle example: http://jsfiddle.net/Lyfr5/1/
i hope it can help you to understand. Bye
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.