垂直居中,水平放置左半部分

时间:2014-10-16 06:32:45

标签: css

如何将容器的“位置”垂直居中?水平它应该在屏幕的左半部分居中(不知道如何更好地解释)。

JSFiddle: http://jsfiddle.net/gbgopon2/1/

<div id="background"></div>
<div id="overlay">
    <div id="position"></div>
</div>

CSS:

#background {
    background-color: #ddd;
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 0;
}

#overlay {
    position: absolute;
    height: 100%;
    background-color: #fff;
    width: 100%;
    top: -3em;
    -webkit-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.3);
    -moz-box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.3);
    box-shadow: 0px 3px 5px 0px rgba(0,0,0,0.3);
    z-index: 1;
}

#position {
    width: 100px;
    height: 50px;
    background: red;
}

2 个答案:

答案 0 :(得分:1)

此添加应垂直对齐div并在左半部分对齐:

#position {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 25%;
    right: 75%;
    margin: auto -50px; /* width / 2 */
}

小提琴:http://jsfiddle.net/gbgopon2/5/

答案 1 :(得分:1)

您也可以使用jQuery来完成它。以下代码将在页面加载和窗口大小调整时自动居中div(如您所述)。

Fiddle

上的演示
function position() {
  var width = $('#position').css('width').slice(0, -2) / 2;
  var height = $('#position').css('height').slice(0, -2) / 2;
  var fWidth = ($(window).width()) / 4;
  var fHeight = $(document).height() / 2;
  var top = fHeight - height;
  var left = fWidth - width;

  $('#position').css({
    'top': top + 'px',
    'left': left + 'px'
  });
}

position();

$(window).resize(function() {
  position();
});
相关问题