1

我有以下 HTML 作为标题。和是.left.right跨度。我有 .left 的特定宽度,但.text宽度并不总是相同。我想为 .left (固定宽度)和 .left 设置背景.right.right应该获得父元素(h1)中的所有剩余空间。那怎么办?

<h1>
    <span class="left"></span>
    <span class="text">Text</span>
    <span class="right"></span>
</h1>

我正在尝试遵循不起作用的 CSS:

.left{
    background: yellow;
    width: 30px;
    height: 20px;
    display: inline-block;
}

.right{
    display: inline-block;
    background: blue;   
}

这是 JSFiddle 链接:http: //jsfiddle.net/jMR8u/

这是我想要得到的:在此处输入图像描述

这个想法是在h1中设置一个背景图像,除了.text跨度,问题是我不能为.text设置背景,否则会更容易。

4

5 回答 5

2

此版本将拉伸以适应内容.text并且应该是跨浏览器的。

您可以通过将蓝色(右)背景设为以下边框来伪造它.text

.text { border-right: 1000px solid; }

然后,.right向左移动 1000px:

.right { margin-left: -1000px; }

给 一个宽度.left,使每个元素inline-block,隐藏右侧多余的蓝色边框,并确保.text不要.right换行:

.left { width: 200px; }
.left, .text, .right { display: inline-block; }
h1 { overflow: hidden; white-space: nowrap; }

并给它颜色!

body { background: green; }
.left { background: red; }
.text { border-color: blue; }

这是一个 JSFiddle演示

JSFiddle 的屏幕截图

于 2012-12-05T22:39:55.687 回答
1

如果我解释你的形象正确..这就是答案http://jsfiddle.net/jMR8u/4/

h1{
    border: 1px solid red;
    position: relative; 
}

.left{
    background: yellow;
    width: 30px;
    height: 20px;
    display: inline-block;
}

.right{
    display: inline-block;
    background: blue;
    position: absolute; 
    z-index: 99;
    height: 20px;
    width: 100%;
}
​.text {
    height: 20px;
    width: 150px;
    display: inline-block;
    position: relative;
    z-index; 101;
}​

好的,然后使用带有 z-index 和定位的层 ..

于 2012-12-05T21:47:55.740 回答
1

您可以使用 flexbox(但使用新语法)。可悲的是,它目前只适用于Chrome 和 Opera,所以它的用处有限:

h1 { display: -webkit-flex; display: flex; }
.left { width: 30px; }
.right { flex: 1; -webkit-flex: 1; } /* This makes it fluid. */
.left { background: yellow; }
.right { background: blue; }

这是一个 JSFiddle 演示:http: //jsfiddle.net/FN7vQ/

于 2012-12-05T21:51:11.270 回答
1

如果您可以将宽度设置为 .text 跨度和 h1 元素。

body{
background:green;
}

h1{
    border: 1px solid red;
    display:table;
    width:100%;
}

.left{
    background: yellow;
    width: 30px;
    display: table-cell;
}

.right{
    display: table-cell;
    background: blue;
}
.text {
    display:table-cell;
    width: 150px;   
}
于 2012-12-05T22:24:27.070 回答
0

如果我正确理解了您的要求。你应该改变你的标记如下

h1 {
  background: #660000;
  padding-left: 30px;
  line-height: 1.1;
}
h1 span {
  background: #fff;
  padding: 0 3px;
  color: #600;
}
<h1>
  <span>
  Lorem, ipsum dolor. you are doing great  
  </span>  
</h1>

CSS在下面

于 2018-03-08T15:12:45.240 回答