如何使用CSS将宽度自动设置为绝对位置

时间:2018-10-06 05:29:44

标签: html css

我现在正在使用position:absolute;,我想使宽度自动(根据内容),但是由于position:absolute;,我无法width:auto;

$('.wishlistMessage').text('Your product added to wishlist')
                                   $('.wishlistMessage').show();
                                   
.wishlistMessage{position: fixed;
   bottom: 25px;
   left: 0;
   right: 0;
   margin-left: auto;
   margin-right: auto;
   background: rgba(0, 0, 0, 0.8);
   color: #fff;
   padding: 12px 25px;
   display: inline;
   width: auto;
   text-align: center;
   border-radius: 5px;
   z-index: 10000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wishlistMessage">Your product added to wishlist</div>

1 个答案:

答案 0 :(得分:3)

带有position: absolute的元素将适合其内容的大小。由于您使用left: 0right: 0,因此该元素被拉伸到两侧。删除其中之一(我已经删除了右侧),将解决问题:

$('.wishlistMessage').text('Your product added to wishlist')
$('.wishlistMessage').show();
.wishlistMessage {
  position: fixed;
  bottom: 25px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 12px 25px;
  text-align: center;
  border-radius: 5px;
  z-index: 10000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wishlistMessage">Your product added to wishlist</div>