I have a DIV containing an image and a second DIV. The parent DIV is set to position: absolute;
the child DIV is set to position: relative
. The idea is that I display my photo caption on top of my image.
The child DIV
should have 100%
width of the parent, minus 10px
on the left, right and bottom, plus a black background.
.article-container {
position: relative;
}
.photo-caption {
width: 100%;
background-color: black;
position: absolute;
bottom: 0px;
margin-right: 10px;
margin-left: 10px;
margin-bottom: 10px;
}
<div class="span15 article-container">
<img src="images/example-image-1.png" />
<div class="photo-caption">This is the subtitle text on top.</div>
</div>
The left margin bumps .photo-caption
outside the bounds of .article-container
. The right margin doesn't seem to have any effect.
I've also tried fixing this with box-sizing
. It seems to get the width of .photo-caption
down to the parent width but there's still the overhang.
Width 100% On the other hand, if you specify width:100%, the element's total width will be 100% of its containing block plus any horizontal margin, padding and border (unless you've used box-sizing:border-box, in which case only margins are added to the 100% to change how its total width is calculated).
Answer 50faea7446ce3ec6a60004cf You cannot see the effect of margin-right because the 'width' property of div causes the margin of div to have more than 10px distance from the right wall of the body. Consequently, it causes the margin-right property not to have any visual effect.
No, element width does not include padding, margin, or border.
The width and height properties include the content, padding, and border, but do not include the margin.
It's better if you remove width:100%
. write like this:
.photo-caption { left:0; right:0; background-color: black; position: absolute; bottom: 0px; margin-right: 10px; margin-left: 10px; margin-bottom: 10px; }
An absolutely positioned element is positioned with top
, left
, right
and bottom
, not with margin
.
The problem is that width=100%
would give photo-caption
exact width of article-container
; adding margins (or padding) would not affect width calculation. You can do this yourself using the css calc()
so the style become:
.photo-caption {
width: calc(100% - 20px); // 20 = right margin + left margin
background-color: black;
position: absolute;
bottom: 0px;
margin-right: 10px;
margin-left: 10px;
margin-bottom: 10px;
}
Note that you might want to check for calc() browser support here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With