简体   繁体   English

CSS灵活布局:灵活的左列和可变的固定右列

[英]CSS flexible layout: flexible left column and variable fixed right column

I want to display the content of the div element in a single row. 我想在单行中显示div元素的内容。 However the width of the ul element is unknown because it can have a number of child li elements. 但是,ul元素的宽度是未知的,因为它可以具有许多子li元素。 The h2 would always occupy the rest of the space. h2将始终占据其余空间。 each li element has a width of 20px. 每个li元素的宽度均为20px。

It would look something like this: 它看起来像这样:

|----h2------------|li|li|li||
|----h2---------------|li|li||

HTML: HTML:

<div>
<h2>name</h2>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>

I have found numerous solutions on the internet but not sure which to choose (proper solution vs hacks). 我在互联网上找到了许多解决方案,但不确定要选择哪种解决方案(正确的解决方案vs hacks)。 browser compatibility is not an issue, it only needs to work on the latest version of chrome. 浏览器兼容性不是问题,它只需要在最新版本的chrome上运行即可。

Update: There will be multiple rows of div elements and the li elements should align. 更新:div元素将有多行,并且li元素应对齐。

You could float the h2 left, and the ul right. 您可以向左浮动h2 ,向右浮动ul

div h2 { float: left; }
div ul { float: right; }

The simplest, most compact and straight forward way is to use floats. 最简单,最紧凑,最直接的方法是使用浮点数。 If you know your elements will be different sizes, but you don't know exactly what they will be, there are 2 completely flexible ways to go about this. 如果您知道元素的大小会有所不同,但是您不知道它们的确切大小,则有2种完全灵活的方法可以解决此问题。

This would be how to do it using display: table : 这将是使用display: table

http://jsfiddle.net/8uTfp/1/ http://jsfiddle.net/8uTfp/1/

div {
    display: table;
    width: 100%;
}

h1, ul {
    display: table-cell;
    vertical-align: middle;
}

ul {
  text-align: right;
}

li {
  display: inline-block;
}

This would be how to do it using flexbox: 这将是使用flexbox的方法:

http://jsfiddle.net/8uTfp/ http://jsfiddle.net/8uTfp/

div {
  display: -moz-box;
  display: -webkit-flexbox;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-align: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
}

ul {
  margin-left: auto;
}

li {
  display: inline-block;
}

If the div's height and the list items' height are fixed and known values, you could try the followihg CSS (notice I added css classes): 如果div的高度和列表项的高度是固定的并且是已知值,则可以尝试以下CSS(注意,我添加了CSS类):

.container{
  height: 30px;
  position: relative;
}
.container ul{
  padding: 0; margin: 0;
  /* Other reset rules here ... */
  position: absolute;
  top: 0;
  right: 0;
}
.container ul li{
  display: inline;
  float: left;
  height: 30px;
  /* Other format rules here ... */
}

If you don't specify the div's height, it will be set by the h2 element's metrics, since absolutely positioned elements don't force the layout. 如果未指定div的高度,则它将由h2元素的指标设置,因为绝对定位的元素不会强制布局。 I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM