Я пытаюсь оформить заголовок так, чтобы он выглядел так:
Проблема в том, что когда я пытаюсь добавить цвет фона в h2, он также применяется к содержимому :before и :after и охватывает всю ширину страницы. Я хочу, чтобы это применялось только к h2.
Я попытался добавить div внутри h2 и стилизовать его вместо h2.
.styled-heading {
text-align: center;
font-size: 32px;
background: black;
color: white;
}
.styled-heading:before {
content: " ";
display: inline-block;
margin: 0 0px 8px 0;
background-color: #999;
height: 3px;
width: 140px;
}
.styled-heading:after {
content: " ";
display: inline-block;
margin: 0 0 8px 00px;
background-color: #999;
height: 3px;
width: 140px;
}<h2 class = "styled-heading">Testing Testing</h2>





Я бы сделал это по-другому без псевдоэлемента:
.styled-heading {
font-size: 32px;
color: white;
display:table; /* to make the element fit the content */
margin:auto; /* to center */
/* The border will be the space for the lines*/
border-left:50px solid transparent;
border-right:50px solid transparent;
padding:5px 10px;
background:
/* main background cover only the padding*/
linear-gradient(green,green) padding-box,
/* the Line cover also the border area (width:100% height:3px)*/
linear-gradient(blue,blue) center/100% 3px border-box no-repeat;
}<h2 class = "styled-heading">Testing Testing</h2>Вы также можете иметь каждую строку отдельно, если хотите:
.styled-heading {
font-size: 32px;
color: white;
display:table; /* to make the element fit the content */
margin:auto; /* to center */
/* The border will be the space for the lines*/
border-left:50px solid transparent;
border-right:50px solid transparent;
padding:5px 10px;
background:
/* main background cover only the padding*/
linear-gradient(green,green) padding-box,
/* the Line cover also the border area*/
linear-gradient(blue,blue) left center/50% 3px border-box no-repeat,
linear-gradient(red,red) right center/50% 3px border-box no-repeat;
}<h2 class = "styled-heading">Testing Testing</h2>Спасибо Темани! Это именно то, что я искал. Я попытался заменить линейный градиент просто «черным», но это не сработало. Нужно ли использовать линейный градиент или можно просто использовать сплошной цвет?
@ cjk47 вы должны использовать градиент, но поскольку я указываю один и тот же цвет, это похоже на использование сплошного цвета, но весь трюк основан на градиенте
Псевдоэлемент - не способ сделать это. Псевдоэлементы являются частью элемента. Это работает:
.header-pinch {
position: relative;
height: 3px;
width: 500px;
z-index: 1;
overflow: visible;
background: grey;
}
.header-pop {
position: relative;
z-index: 2;
background: black;
color: white;
width: fit-content;
padding: 5px;
margin: auto;
transform: translateY(-50%);
}<br/>
<div class = "header-pinch">
<h2 class = "header-pop">TESTING</h2>
</div>
Цвет фона не применяется к
::beforeи::after. Они находятся внутриh2, который (потому что этоdisplay: block) охватывает ширину своего родительского элемента.