Home > database >  Background image is not visible using before property in css
Background image is not visible using before property in css

Time:12-20

* {
  margin: 0px;
  padding: 0px;
}

.navigation {
  background-color: black;
  display: flex;
}

.navigation li {
  display: inline;
  color: white;
  padding: 10px;
  list-style: none;
  font-size: 1.5rem;
}

.navigation::before {
  position: absolute;
  content: "";
  opacity: 0.5;
  z-index: -1;
  background: url('http://placekitten.com/200/200');
}
<div >
  <ul>
    <li>Home</li>
    <li>About Us</li>
    <li>Register</li>
    <li>Contact Us</li>
  </ul>
</div>

I want to add a background image to my content but it is not appearing using the 'before' property in navigation as.... .navigation::before{image code for background}.

CodePudding user response:

You have two problems which each, independently, cause the problem you are seeing. You need to fix both of these.

Negative z-index

You gave ::before a negative z-index, which puts it under the .navigation element's content. The black background colour covers up the ::before element so you can't see it.

Zero dimensions

You haven't set the height and width, not have you used position: absolute in combination with left, right, top and bottom so the size of ::before is based on its content.

The content of ::before is an empty string, so no size at all is needed to display that, so it gets rendered 0px by 0px.

There are no pixels in which the image is rendered.

You need to give it a size somehow.

CodePudding user response:

I think this will help you

* {
  margin: 0px;
  padding: 0px;
  --nav-height: 2rem;
}

.navigation {
  background-color: black;
  display: flex;
  overflow: hidden;
  height: var(--nav-height);
  align-items: center;
}

.navigation li {
  display: inline;
  color: white;
  padding: 10px;
  list-style: none;
  font-size: 1.5rem;
}

.navigation::before {
  position: absolute;
  content: "";
  opacity: 0.5;
  background: url('http://placekitten.com/200/200');
  background-size: cover;
  top: 0;
  left: 0;
  width: 100%;
  height: var(--nav-height);
}
<div >
  <ul>
    <li>Home</li>
    <li>About Us</li>
    <li>Register</li>
    <li>Contact Us</li>
  </ul>
</div>

  • Related