简体   繁体   中英

Align a Gradient to center in CSS

I want the gradient to be in the center of the page and text to be on that gradient.

 #grad1{ background-image: linear-gradient(to right bottom ,rgb(103, 53, 168),rgb(32, 147, 179)); position: fixed; align-self: center; }
 <h1 id=grad1>Hello Guys</h1>

I want this heading to be on the top and at the center also place on the gradient. Also on scrolling I don't want it to go up with the page instead it should be visible at any time even if I have scrolled to the bottom of the page.

Considering the ' h1 ' tag is not inside any block-level ancestor and ' fixed ' position property given on the ' h1 ' tag, the containing area of the ' h1 ' tag would be established by the viewport or the page area.

Mostly, Containing area is the content area of the element's nearest block-level ancestor. In our case, containing area is the viewport.

So, if we apply left and top properties on the h1 tag, this would we calculated based on the viewport width.

#grad1 {
  background-image: linear-gradient(to right bottom ,rgb(103, 53, 168),rgb(32, 147, 179));
  position: fixed;
  align-self: center;
  left: 50%;
  top: 0;
}

The above will move the ' h1 ' tag 50% left of the viewport width. Now, we need to move back the h1 tag text left by half of it's width. This could be achieved using transform-translate property.

For example -

#grad1 {
  background-image: linear-gradient(to right bottom ,rgb(103, 53, 168),rgb(32, 147, 179));
  position: fixed;
  align-self: center;
  left: 50%;
  top: 0;
  transform: translate(-50%, 0);
}

Hope this helps you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM