CSS 如何在保持垂直位置的同时使 div 与父级的右侧对齐?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12729170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:23:59  来源:igfitidea点击:

How to make a div align to the right side of the parent while maintaining its vertical position?

csspositioningvertical-alignment

提问by sbichenko

Please refer to this handy diagram I drew:

请参考我画的这个方便的图表:

enter image description here

在此处输入图片说明

div1's height is unknown. div3's width is fluid; it should never overlap div2. Both div1and div2have the same width and are horizontally centered via margin: auto. How can I position div3so that it aligns to the right side of body(no matter how wide bodyis) while sharing vertical position with div2? (Using CSS)

div1身高不详。div3的宽度是流动的;它永远不应该重叠div2。二者div1div2具有相同的宽度,并通过在水平方向为中心margin: autodiv3在与共享垂直位置的同时,如何定位以使其与 的右侧body对齐(无论有多宽bodydiv2?(使用 CSS)

回答by Gabriele Petrioli

.div1{
    margin:0 auto;
    width:100px;
    height:50px;
    border:5px solid #995555;
}
.div2{
    width:100px;
    margin:0 auto;
    border:5px solid #aaaa55;
    height:200px;
}
.div3{
    float:right;
    width:50px;
    height:100px;
    border:5px solid cyan;
}
<div class="div1">div1</div>
<div class="div3">div3</div>
<div class="div2">div2</div>

Demo also at http://jsfiddle.net/XjC9z/1/

演示也在http://jsfiddle.net/XjC9z/1/

回答by Filipa Lacerda

Like this?

像这样?

HTML:

HTML:

<div id='container'>
    <div id='first'>1</div>
    <div id='second'>2</div>
    <div id='third'>3</div>
</div>?

CSS:

CSS:

#container{
    width: 100px;
    margin:0 auto;
}

#first{
    border: 1px solid #ff55ff;
}
#second{
    border: 1px solid #55ff77;
}

#third{
    border: 1px solid #448855;
}
#first,
#second{
    width: 50px;
    clear:both;

    float:left;
}

#third{
    clear:none;
    float: left;
}

?

?

See this fiddle: http://jsfiddle.net/zaNvR/1/

看到这个小提琴:http: //jsfiddle.net/zaNvR/1/

回答by Lowkase

A simple div grid would do the trick:

一个简单的 div 网格可以解决问题:

http://jsfiddle.net/NUGPv/

http://jsfiddle.net/NUGPv/

<div class="con">
    <div class="lft">div 1</div>
    <div class="rgt"></div>
</div>
<div>
    <div class="lft">div 2</div>
    <div class="rgt">div 3</div>    
</div>?

.con { overflow:hidden; }
.lft { width:100px; height:100px; float:left; }
.rgt { width:100px; height:100px; float:left; }

Simply leave the the top right cell empty.

只需将右上角的单元格留空即可。