问题描述
我有一个容器div,它有动态宽度,它根据屏幕分辨率而变化。在这样的div中,我有另一个元素具有固定的高度和宽度。我可以给这样的元素a margin:0 auto;
并在中间水平对齐,但这个技巧不工作,在中间垂直对齐,作为容器的高度div保持相同(它不是固定的高度,它取决于div内的内容)。因此,我想以某种方式应用相同的边距去左右,到顶部和底部,当用户更改分辨率。因此,在所有方面应该有相同的动态利润率?
这将是很好的基于css的解决方案,但如果这是不可能的,jQuery是好的。 / p>
基本上,我需要的是计算右边或左边的边距,并将这些值应用到顶部和底部边距。
我不认为你需要一个JavaScipt / jQuery解决方案。你可以使用CSS。
查看 vertical-align
属性。您需要检查其注意事项和要求,因为它需要 inline
/ inline-block
。
你想要的是什么:
#center-element {
display:inline-block;
height:300px; //你的固定高度
width:250px; // your fixed width
margin-left:auto;
margin-right:auto;
vertical-align:middle;
}
查看。它提供了对 vertical-align
属性及其使用及其限制的非常好的描述。
UPDATE
根据您的意见,如果您想)应用左边距或右边距也是顶部边距,可以使用以下jQuery执行此操作:
$ ).ready(function(){
var $ ele = $(#centered-element);
var marginL = $ ele.css(margin-left);
$ ele.css({
margin-top:marginL,
margin-bottom:marginL
});
});
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.
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
});
});
这篇关于在响应式设计中将“top”和“bottom”作为“right”和“left”的边距给予相同的边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!