【问题标题】:How to vertically align something with the element in front of its parent如何将某些东西与其父元素前面的元素垂直对齐
【发布时间】:2015-10-02 17:29:20
【问题描述】:

鉴于此 html:

<header>Some header</header>
<div>
    <div class="right-of-header">should be to the right of header</div>
    <div>Some mor text is here</div>
</div>

我希望第一个内部 div 的内容出现在标题的右侧。

这是否可能,无需使用 javascript 来实际移动 DOM 元素?

我刚刚发现了这个问题:Position one element relative to another in CSS 但这对我不起作用,因为我不知道标题元素的大小和宽度。换句话说,解决方案应该响应不同的布局。

有一个jsfiddle for it here

【问题讨论】:

    标签: css responsive-design css-float vertical-alignment


    【解决方案1】:

    这可行:https://jsfiddle.net/djgmj89c/

    这个想法是

    1. 制作float: left

    2. 制作应该放在右边的内容float: right;

    3. 在应该向右的元素之后创建元素clear: both;

    导致以下css:

    header {
        float: left;
    }
    .clear {
        clear: both;
    }
    .right-of-header {
        float: right;
    }
    

    【讨论】:

    • 不,这只是右对齐。我希望它在相同的垂直位置,但在标题的右侧。我更新了小提琴以包含一个示例。
    • 我使用了您的方法并清理了您的答案。我希望你可以接受激烈的编辑。
    • 在我实际使用的版本中,将clear类替换为:header+* :not(.right-of-header):first-of-type { clear: both; }
    【解决方案2】:

    这里的问题是 div 的默认 display 设置为 block

    我的建议是修改您的 html。将header显示 值更改为display: inline-block;,将right-of-header 的值更改为display: inline;

    如下:

    <style>
    header {
        font-size: 30px;
        display: inline-block;
    }
    
    .right-of-header {
        font-size: 8px;
        width: 50px;
        display: inline;
    }
    </style>
    
    <header>Some header</header>
    <div class="right-of-header">should be to the right of header</div>
    <div>
        <div>Some mor text is here</div>
    </div>
    

    这里有一个演示:https://jsfiddle.net/z1c9Lgzo/

    编辑:

    由于您无法修改 html,另一种解决方案 (我完全反对,但似乎找不到其他方法)相对更改position。像这样:

    .right-of-header {
        font-size: 8px;
        width: 50px;
        float: right;
        position: relative;
        top: -40px;
    }
    

    这里有一个演示:https://jsfiddle.net/g4srpcpn/

    您可能需要调整 top 值以更好地对齐。

    【讨论】:

    • 不幸的是我不能移动 div 元素。好吧,我可以,但这会在其他地方造成问题......
    • 我添加了另一个答案。老实说,正如解释的那样,我不喜欢因对齐问题而改变位置。
    • 我理解并同意您的担忧,但这似乎是一个可行的选择。
    【解决方案3】:

    如果您有一个具有相对位置的父容器,也许这可以帮助您。

    <header>Some header</header>
    <div>
        <div class="right-of-header">should be to the right of header</div>
        <div>Some mor text is here</div>
    </div>
    
    <style>
    header {
        font-size: 30px;
        display: inline-block
    }
    
    header + div{
        display: inline-block;
        float: right;
    }
    
    header + div > div:nth-of-type(2){
        position: absolute;
        left: 0;
        padding: 10px;
    }
    
    .right-of-header {
        font-size: 8px;
        width: 50px;
    }
    </style>
    

    https://jsfiddle.net/0wqud60n/1/

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2013-06-18
      • 2021-09-18
      • 2014-04-02
      • 2015-07-15
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多