gpt4 book ai didi

html - 使用 CSS 在 div 之前和之后使用不同的颜色

转载 作者:技术小花猫 更新时间:2023-10-29 12:06:42 26 4
gpt4 key购买 nike

对于一个网站,我试图让容器之前的元素以不同于容器之后的元素的颜色出现。我想得到以下结果:

Example of the result

我试过这个:CSS :before :after background color .还有很多其他的东西,但都没有成功。我最终得到了以下代码:

.section {
width: 100%;
}

.section .container {
background-color: #fff;
width: 250px;
margin: 0 auto;
text-align: center;
}

.section .container::before {
background-color: red;
content: ' ';
}

.section .container::after {
background-color: blue;
content: ' ';
}

.section .container h1 {
padding: 10px;
}
<div class="section">
<div class="container">
<h1>Hello world.</h1>
</div>
</div>

结果只是白色。

最佳答案

这里有一个更简单的背景着色想法:

.section {
background:linear-gradient(to right,red 50%,blue 0);
}

.section .container {
background-color: #fff;
width: 250px;
margin: 0 auto;
text-align: center;
}

.section .container h1 {
padding: 10px;
}
<div class="section">
<div class="container">
<h1>Hello world.</h1>
</div>
</div>

您仍然可以在只有一个容器和多个背景的情况下进行更多优化:

.container {
background:
linear-gradient(#fff,#fff) center/250px 100% no-repeat,
linear-gradient(to right, red 50%, blue 0);
text-align: center;
padding:10px 0;

}

.container h1 {
margin:0 auto;
max-width:250px;
}
<div class="container">
<h1>Hello world.</h1>
</div>

另一种透明方式:

.container {
background:
linear-gradient(red,red) left,
linear-gradient(blue,blue) right;
background-size:calc(50% - (250px/2)) 100%;
background-repeat:no-repeat;
text-align: center;
padding:10px 0;
}

.container h1 {
margin:0 auto;
max-width:250px;
}

body {
background:pink;
}
<div class="container">
<h1>Hello world.</h1>
</div>

透明语法的另一种语法:

.container {
background:
linear-gradient(to right,
red calc(50% - (250px/2) - 1px),transparent calc(50% - (250px/2)),
transparent calc(50% + (250px/2)),blue calc(50% + (250px/2) + 1px));
text-align: center;
padding:10px 0;
}

.container h1 {
margin:0 auto;
max-width:250px;
}

body {
background:pink;
}
<div class="container">
<h1>Hello world.</h1>
</div>

关于html - 使用 CSS 在 div 之前和之后使用不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784508/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com