Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable :hover on margin

Is there any possibility to enable the :hover css effect also on the "margin area" of an object? I found a dirty solution working with an extra div inside, but is there something more elegant for this simple structure:

<ul>
  <li><a>Hello</a></li>
  <li><a>Hello</a></li>
</ul>

CSS

ul {
  list-style: none; 
  margin: 0px; 
  padding: 0px;
}

li {
  margin: 5px 100px;
  background-color: #f1f1f1;
}

li:hover a {
  color: red;
}

#dirty {
  padding: 0px 100px;
  margin: 0px -100px;
}

Hey is my working dirty example: https://jsfiddle.net/equalsound/wn4ctxvh/

If possible, a css only solution would be lovely.

like image 239
equalsound Avatar asked Feb 12 '18 18:02

equalsound


2 Answers

As asked in the comments to your question, here is a working answer, using pseudo-elements to fill the 100px side margin:

ul {
  list-style: none; 
  margin: 0px; 
  padding: 0px;
}

li {
  position: relative;
  margin: 5px 100px;
  background-color: #f1f1f1;
}

li::before,
li::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100px;
}

li::before {
  right: 100%;
}

li::after {
  left: 100%;
}

li:hover a {
  color: red;
}
<ul>
  <li><a>Hello</a></li>
  <li><a>Hello</a></li>
</ul>
like image 191
chriskirknielsen Avatar answered Oct 01 '22 07:10

chriskirknielsen


Just for fun, an alternative using transparent borders that's a little less practical due to the use of background-clip: padding:

ul {
  list-style: none; 
  margin: 0px; 
  padding: 0px;
}

li {
  margin: 5px 100px 5px 0;
  border-left: 100px solid transparent;
  background-clip: padding-box;
  background-color: #f1f1f1;
}

li:hover a {
  color: red;
}
<ul>
  <li><a>Hello</a></li>
  <li><a>Hello</a></li>
</ul>

Although, you can obviate the need for that if you can afford to make the a elements blocks and apply the background color to them instead:

ul {
  list-style: none; 
  margin: 0px; 
  padding: 0px;
}

li {
  margin: 5px 100px 5px 0;
  border-left: 100px solid transparent;
}

li a {
  display: block;
  background-color: #f1f1f1;
}

li:hover a {
  color: red;
}
<ul>
  <li><a>Hello</a></li>
  <li><a>Hello</a></li>
</ul>
like image 32
BoltClock Avatar answered Oct 01 '22 07:10

BoltClock