如何根据页面中心定位元素?

时间:2015-06-22 15:45:02

标签: html css

我有2个HTML元素

// the view model bound to the view
var vm = {
   branches: ko.observableArray([]),
   selectedBranch: ko.observable(),
   departments: ko.observableArray([]),
   selectedDepartment: ko.observable()
}

// subscription to listen to changes to the selected branch
vm.selectedBranch.subscribe(function(current, last){
   if(!current) return; // do nothing if nothing is selected
   if(current == last) return; // do nothing if nothing changed

   $.ajax({
      type: 'GET',
      url: '/api/Departments/GetDepartment/' + current.BranchId,
      contentType: 'application/json'
   })
  .then(function(result){
      vm.departments(result)
   });
}

// load the list of branches
$.ajax({
   type: 'GET',
   url: '/api/Branches',
   contentType: 'application/json'
})
.then(function(result){
   vm.branches(result); // populate branch observable array
   ko.applyBindings(vm);// bind view model to view
});

我想将这些元素放置在距离页面中心X个像素的位置。例如,我想将<h1 id="prev">TITLE1</h1> <h1 id="curr">TITLE2</h1> 50像素放在中心的左侧,将TITLE1 50像素(相同的空间量)放在中心的右侧。如下所示:

TITLE2

4 个答案:

答案 0 :(得分:3)

你可以这样做:

&#13;
&#13;
#prev {float: left; margin: 0; width: 50%; text-align: right; margin-left: -50px;}
#curr {float: right; margin: 0; width: 50%; text-align: left; text-indent: 50px;}
&#13;
<h1 id="prev">TITLE1</h1>
<h1 id="curr">TITLE2</h1>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

另一种方法:

&#13;
&#13;
#headers-set{
    text-align:center;
}
#prev{
    display:inline-block;
    margin-right:50px;
}
#curr{
    display:inline-block;
    margin-left:50px;
}
&#13;
<div id="headers-set">
  <h1 id="prev">TITLE1</h1><h1 id="curr">TITLE2</h1>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

如果您知道&#34;标题元素&#34;的宽度,您还可以使用position absolute; left:50% - 然后left-margin将一个框50px向右移动,另一个框移动到另一个框左侧boxWidth+50

#prev{
    position:absolute;
    left:50%;
    margin-left:-200px;
    width:150px;
    background:blue;
}

#curr{
    position:absolute;
    left:50%;
    margin-left:50px;
    width:150px;
    background:red;
}

https://jsfiddle.net/ordccd40/

没有固定宽度的绝对方法:)

https://jsfiddle.net/ordccd40/1/

#prev{
    position:absolute;
    right:50%;
    margin-right:50px;
    background:blue;
}

#curr{
    position:absolute;
    left:50%;
    margin-left:50px;
    background:red;
}

答案 3 :(得分:0)

&#13;
&#13;
body{
  text-align: center;
}
#prev,#curr{
  display: inline;
}
#prev{
  position: relative;
  left: -50px;
}
#curr{
  position: relative;
  left: 50px;
}
&#13;
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <h1 id="prev">TITLE1</h1>
  <h1 id="curr">TITLE2</h1>
</body>
</html>
&#13;
&#13;
&#13;

这种方式使用最少的代码。 JSfiddle.

body{
  text-align: center;
}
#prev,#curr{
  display: inline;
}
#prev{
  position: relative;
  left: -50px;
}
#curr{
  position: relative;
  left: 50px;
}