I've done a simple little exercise with jQuery, where I have some <h2>
that change color when I press a button. It works for me but the color takes up the entire browser window and I was wondering if there was a way to change just the background color to where the letters end.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ejercicio 4</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function ()
{
$('button').click(function ()
{
$('.objetos').css("background-color","yellow");
});
});
</script>
</head>
<body>
<h2>Lenguaje C</h2>
<h2 class="objetos">Java</h2>
<h2 class="objetos">JavaScript</h2>
<h2 class="objetos">PHP</h2>
<button>Orientados a objetos?</button>
</body>
</html>
You can use
display: table
. This way, the background will fit the content and you won't be placed on the same line as withdisplay: inline
ordisplay: inline-block
.Your modified example:
You can use display inline-block, this will allow the background to only go as far as the text. If you want them to be one below the other then you put each h2 inside a div.
example below
The problem is that the h2 have by default the css property "display" with value "block".
That is, they occupy all the available space of the container horizontally, a possible solution would be to change this property as follows: