如何设置div的背景颜色宽度?

时间:2013-11-19 15:25:43

标签: html css

我有两个<div> s具有相同的背景颜色。如何设置背景的宽度?

预期结果

enter image description here

这是HTML:

<div>
    <span>100% width of background</span>
</div>
<div>
    <span>75% width of background</span>
</div>

我尝试使用CSS做什么:

div {
    background-color: #fc0;
    margin: 2px;
}
div:last-child {
    background-size: 75%;
}

jsFiddle,当然。

设置width div的{​​{1}}是否可行?

5 个答案:

答案 0 :(得分:5)

您可以使用硬停止的背景渐变。

http://jsfiddle.net/isherwood/ZWrmn

div:last-child {
    background: linear-gradient(left, green 0, green 75%, transparent 75%);
}

答案 1 :(得分:1)

你不能用简单的background-color来做,但你可以用CSS渐变来做。

background-color始终被视为整个元素的单一纯色,但渐变被视为图像,并且可以调整大小。您还可以使用渐变来执行其他操作,例如分层多个渐变,而使用简单background-color无法完成。

答案 2 :(得分:1)

我会使用1px图像作为背景,例如background: url(1px.png) repeat-y;,然后您可以将background-size:75%;设置为现在的图像。让生活更轻松,更少/更简单的代码。

答案 3 :(得分:0)

你可以使用渐变:

background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzFlNTc5OSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjY5JSIgc3RvcC1jb2xvcj0iIzFlNTc5OSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjcwJSIgc3RvcC1jb2xvcj0iIzFlNTc5OSIgc3RvcC1vcGFjaXR5PSIwIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiMxZTU3OTkiIHN0b3Atb3BhY2l0eT0iMCIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(left,  rgba(30,87,153,1) 0%, rgba(30,87,153,1) 69%, rgba(30,87,153,0) 70%, rgba(30,87,153,0) 100%);
background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(30,87,153,1)), color-stop(69%,rgba(30,87,153,1)), color-stop(70%,rgba(30,87,153,0)), color-stop(100%,rgba(30,87,153,0)));
background: -webkit-linear-gradient(left,  rgba(30,87,153,1) 0%,rgba(30,87,153,1) 69%,rgba(30,87,153,0) 70%,rgba(30,87,153,0) 100%);
background: -o-linear-gradient(left,  rgba(30,87,153,1) 0%,rgba(30,87,153,1) 69%,rgba(30,87,153,0) 70%,rgba(30,87,153,0) 100%);
background: -ms-linear-gradient(left,  rgba(30,87,153,1) 0%,rgba(30,87,153,1) 69%,rgba(30,87,153,0) 70%,rgba(30,87,153,0) 100%);
background: linear-gradient(to right,  rgba(30,87,153,1) 0%,rgba(30,87,153,1) 69%,rgba(30,87,153,0) 70%,rgba(30,87,153,0) 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#001e5799',GradientType=1 );

CSS gradient generator

jsfiddle

答案 4 :(得分:0)

你应该将你的CSS更改为:

div {
    background-color: #fc0;
    margin: 2px;
}
 div:last-child {

      background-image: -webkit-linear-gradient(left, #fc0, #fc0 75%, transparent 75%,     transparent 100%)
}