我想要一个div,在这个div里面必须是一个有颜色的字段。所以我希望有div,例如,200 px200 So,并设置背景颜色:gray,大小为100 px100 So,从位置50 px50px开始。
请看这个代码片段:
div{
background-color: gray;
background-size: 100px 100px;
background-position: 50px 50px;
min-width:200px!important;
min-height:200px!important;
max-width:200px!important;
max-height:200px!important;
padding:50px;
}
<div>some text</div>
所以当你看到背景颜色填充了所有的div宽度和高度。这是否可能使背景只占50%?
注意:红色区域应该是透明的。
发布于 2016-09-22 01:52:33
我们可以使用线性梯度、background-size
和background-position
来实现这一效果。
卡尔克将背景的大小减小了100 in,当中心为50 in时,div周围的透明空间减少了50 in。
全例
第二个div显示div的真实大小,20vw
宽度和高度显示div如何调整大小。
div {
background: linear-gradient(to bottom, grey 0, grey 100%) no-repeat;
background-size: calc(100% - 100px) calc(100% - 100px); /* Reduce height of background by 100px and width by 100px*/
background-position: center;
padding: 80px; /* 50px border + 30px additional padding */
width: 20vw;
height: 20vw;
min-width: 200px;
min-height: 200px;
}
div.no-gradient {
background: grey;
}
/*For example*/
html,
body {
height: 100%;
margin: 0;
}
body {
background: linear-gradient(to bottom, black 0%, white 100%);
}
div {
float: left;
}
<div>some text</div>
<div class="no-gradient">I am the same size as the other div</div>
发布于 2016-09-22 01:12:36
其他的答案提供了很好的解决办法。这是一个冷酷的事实:
不能为元素的半内容区域设置背景色
背景颜色应用于元素内容区域。不能将背景色应用于元素内容区域的一半。
Mozilla解释了这一点:
内容区域是包含元素真实内容的区域。它通常具有背景、颜色或图像(按此顺序,隐藏背景色的不透明图像),并且位于内容边缘;其尺寸是内容宽度、内容框宽度、内容高度或内容框高度。
元素的内容区域正好有一个背景色。颜色可能是透明的,可能是继承的,而不是定义的,或者是完全覆盖的--但始终只有一种,而且只能有一种。
浏览器开发人员工具中的检查元素将帮助您熟悉这一点。
需要创建的效果有很多解决方法,包括嵌套元素、伪元素和粗边框。
发布于 2018-07-28 07:14:48
给你..。
div.container {
width:200px;
background:transparent;
border: 1px solid #a7a7a7;
padding:50px 0;
}
div.inner-container{
background-color:gray;
width: 100px;
padding:25px 0;
margin:auto;
}
<div class="container">
<div class="inner-container">
---some text---
</div>
</div>
https://stackoverflow.com/questions/39627453
复制相似问题