I have an h1 tag in which I want to apply a background color, with the max-width property. But the background color should not be applied based on content width. Can anyone help to resolve this?
Current output:
Expected output: Should remove red mark background color without changing the HTML content(in css with max-width property). Use only css:
h1 {
background-color: yellow;
max-width: 200px;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This paragraph testing 123</h1>
</body>
</html>
CodePudding user response:
Since display:block
behavior always trying to stretch of its container width so your body has 100%. But when you put max-width:200px
it becomes limited by 200px regardless of content inside. With your mention not changing html its not so good but you can try max-width to content Width. So try tweak html or change max-width
h1 {
background-color: yellow;
max-width: min-content;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This paragraph testing 123</h1>
</body>
</html>
CodePudding user response:
h1 {
max-width: 200px;
}
h1>span {
background-color: yellow;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1><span>This paragraph testing 123</span></h1>
</body>
</html>
I thing you can put span tag inside H1 tag
CodePudding user response:
As you don't want to change HTML content, either decrease max-width value or set width in percentage wise with media query for Responsive Design.
h1 {
max-width: 150px;
background-color: yellow;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This paragraph testing 123</h1>
</body>
</html>
h1 {
background-color: yellow;
width: 26%;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>This paragraph testing 123</h1>
</body>
</html>
CodePudding user response:
i faced this problem in client project, I searched many option but its not working properly, then finally I found this solution using "SELECTION" text you can set background cover on Text using JavaScript it support in all browser.
$(document).ready(function () {
let resEle = document.querySelector("h1");
$("h1").hover(
function () {
window.getSelection().selectAllChildren(this);
},
function () {
window.getSelection().removeAllRanges(this);
}
);
});
h1 {
max-width: 200px;
}
h1::selection{
background:yellow;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>This paragraph testing 123 </h1>
</body>
</html>