javascript - 居中 div 之前的 div

标签 javascript jquery html css

我的网站有很多标题。如果有人点击标题,则应在标题(左侧)之前(例如 10 像素)显示一个按钮。

问题是标题应该始终居中——无论按钮是否显示。如果显示/隐藏按钮,标题不应改变其位置。

<html>
  <head>
    <style type="text/css">
      .headline {
        background-color: grey;
        margin-left: auto;
        margin-right: auto;
        margin-bottom: 20px;
        padding: 5px;
        width: 70%;
      }
    </style>
  </head>

  <body>
    <div class="headline">Headline 1</div>
    <div class="headline">Headline 2</div>
  </body>
</html>

fiddle :https://jsfiddle.net/ct11gp3v/

我已经尝试了很多绝对位置......但没有成功。

提前致谢!

最佳答案

只需将按钮粘贴在标题内,并使其成为绝对位置:

.headline {
    background-color: grey;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 20px;
    padding: 5px;
    width: 70%;
    position: relative; /* This will allow the button to be
                           displayed relative to the headline */
}

.headline div{
    position: absolute;
    top: 5px;
    right: 100%;
    margin-right: 10px;
}
<div class="headline">Headline 1 <div>Test</div></div>
<div class="headline">Headline 2</div>

关于javascript - 居中 div 之前的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446004/

相关文章:

javascript - 如何删除人力车直方图中的垂直线?

javascript - JavaScript 中的 ruby​​ 给出 Uncaught SyntaxError : Unexpected identifier

coffeescript - 动态添加元素 - 使用 $(this)

JavaScript 解析 HTML : Get everything inside table tag

html - 如何使用 mod_rewrite 重定向到文档并设置 GET 参数?

电子邮件中的 HTML 格式

javascript - 使用半样式 CSS 的 Font Awesome

javascript - 正则表达式有问题,仅在 JavaScript 中?

javascript - 如何在本地存储中保存和恢复文件对象

javascript - 在 jquery 中一个完成之前停止执行另一个