是否有可能使绝对位置div的宽度足够大,以包含文本,但不更大?我尝试了内联块,但它似乎不起作用,因为一旦我设置了位置:绝对div将获得父元素的最大宽度。
您是否可以建议对子元素进行哪些更改,使其浮动在父div的中心,并且宽度最小,但适合内部的文本字符串。
下面是jsfiddle:http://jsfiddle.net/hmmrfmk0/
<div class='grand-parent'>
<div class='parent'>
    <div class='child'>
        long long long string
    </div>
</div>
.grand-parent {
    position: absolute;
    width:500px;
    height:100px;
    background-color:red;
}
.parent {
    position:relative;
    margin: 0;
    padding: 0;
    width:500px;
    height:100px;
}
.child {
    position:absolute;
    margin:auto;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background-color: #ccccc0;
    border: 1px solid black;
    height:15px;
    display:inline-block;
}谢谢!
发布于 2015-02-17 14:48:05
是的。使用white-space:nowrap并移除上、左、右、下0值以及所需元素的位置。在这种情况下,父div的死中心。
.grand-parent {
  width: 500px;
  height: 100px;
  background-color: red;
  margin-bottom: 10px;
}
.parent {
  position: relative;
  margin: 0;
  padding: 0;
  width: 500px;
  height: 100px;
}
.child {
  position: absolute;
  margin: auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #ccccc0;
  border: 1px solid black;
  height: 15px;
  white-space: nowrap;
}<div class='grand-parent'>
  <div class='parent'>
    <div class='child'>
      long long long string
    </div>
  </div>
</div>
<div class='grand-parent'>
  <div class='parent'>
    <div class='child'>
      long long long string ong long long string
    </div>
  </div>
</div>
发布于 2015-02-17 14:42:07
您的.child类包括左:0和右:0
这将迫使div和它的父级一样宽,内联块不会忽略这一点。
从.child中移除右:0,它将按您的需要工作。
发布于 2015-02-17 14:43:08
试试这个小提琴。如果将父单元格显示为表格单元格,并将垂直对齐置于中间,则可以垂直定位。
.grand-parent {
   position: absolute;
   width:500px;
   height:100px;
   background-color:red;
}
.parent {
   position:relative;
   margin: 0;
   padding: 0;
   width:500px;
   height:100px;
   text-align: center;
   display: table-cell;
   vertical-align: middle;
}
.child {
   background-color: #ccccc0;
   border: 1px solid black;
   height:15px;
   display:inline-block;
   vertical-align: middle;
}https://stackoverflow.com/questions/28563915
复制相似问题