问题
I've got a container div which has got dynamic width, it changes depending on screen resolution. Inside such div I have another element with fixed height and width. I can give such element a margin: 0 auto;
and align it horizontally in the middle, however this trick doesn't work to align it vertically in middle, as height of container div remains same (it's not fixed height, it depends on content inside the div). Therefore I'd like to somehow apply same margins as go to right and left, to top and bottom, when users change resolution. Therefore there should be same dynamic margin on all sides?
It would be good to have css based solution, but if that is not possible, jQuery is good as well.
Basically what I need is to calculate margins of either right or left side and apply those values to top and bottom margins.
回答1:
I don't think you need a JavaScipt/jQuery solution here. You can do this with just CSS.
Look into the vertical-align
property. You will need to review its caveats and requirements, as it requires elements to be inline
/inline-block
.
What you will want is something like:
#centered-element {
display: inline-block;
height: 300px; //your fixed height
width: 250px; // your fixed width
margin-left: auto;
margin-right: auto;
vertical-align: middle;
}
Take a look at this article. It gives a pretty good description of the vertical-align
property, its use and its limitations.
UPDATE
Based on your comments, if you want to (literally) apply the left or right margin to also be the top margin, you can do this using the following jQuery:
$(document).ready(function() {
var $ele = $("#centered-element");
var marginL = $ele.css("margin-left");
$ele.css({
"margin-top": marginL,
"margin-bottom": marginL
});
});
回答2:
if you have fixed width and height of inside element, you may use this little trick
#outside {
position: relative;
}
#inside {
position: absolute;
top: 50%;
left: 50%;
height: 500px;
width: 500px;
margin-top: -250px;
margin-left: -250px;
}
回答3:
This gives a container div floating with a constant margin.
<div>Content</div>
div {
background: #282;
width:90%;
height:90%;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
http://jsfiddle.net/djwave28/tATZU/1/
In addition with reference to content, you can place this inside the container. Upon exceeding the height, a scroll function in CSS can be applied. If not the scroll function of the window will take over.
http://jsfiddle.net/djwave28/tATZU/2/
来源:https://stackoverflow.com/questions/16002325/give-same-margin-to-top-and-bottom-as-margin-of-right-and-left-in-respon