中心对齐绝对div而不使用左:0,右:0,宽度:100%

时间:2017-07-05 09:46:03

标签: html css css3

如何在不使用absolute divleftright的情况下居中width:100%width应该是auto

div{
    position: absolute;
    width: 100%;
    margin: 0 auto;
    display: table;
}

3 个答案:

答案 0 :(得分:2)



.container {
  position: relative;
  width: 300px;
  height: 300px;
  background-color: #EEE;
}
.answer {
  position: absolute;
  width: auto;
  padding: 10px;
  background-color: #CCC;
  
  transform: translate(-50%, -50%);
  margin: 50% 0 0 50%;
}

<div class="container">
  <div class="answer">absolute</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我只是水平居中,因为OP没有说明它是水平居中还是垂直居中

&#13;
&#13;
div {
  position: relative;
  width: 300px;
  height: 200px;
  background-color:blue;
}

p {
  position: absolute;
  margin: 0 50%;
  transform:translate(-50%, 0);
  width: auto;
  background-color: red;
}
&#13;
<div>
  <p> SAMPLE CONTENT </p>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

您可以使用margin来定位div元素。例如:

margin-left: 50%;

或反之亦然。

编辑:以下是解释上述文字的摘要。我希望它有所帮助。

body {
margin: 0;
padding: 0;
background-color: #000;
}

h1 {
color: #fff;
margin-top: 100px;
margin-left: 25%;
}
<html>
<body>
<h1>This is an example</h1>
</body>
</html>

相关问题