Reputation: 12545
I am trying to use CSS+HTML to position a purple block at the top of the viewport. I want the purple block to be horizontally centered and appear on top of anything else. The way my code is organized, other elements (a green button) must appear above the purple block in my HTML file.
I'm using the HTML below. Properly positions the block at the top of the page and on top of other elements. But it is not horizontally centered. How can I make it horizontally centered using CSS?
Plunker here.
<!DOCTYPE html>
<html>
<head>
<style>
.pretty-button {
color: white;
background-color: rgba(17, 175, 29, 0.64);
border-radius: 0.6em;
border: 0.2em solid #73AD21;
padding: 0.5em;
}
.top-block {
position: absolute;
top: 0px;
height: 30px;
width: 60%;
margin: auto;
background-color: purple;
z-index: +1;
}
</style>
</head>
<body>
<button class="pretty-button">Button A</button>
<div id="div1">
<div id="div2">
<div id="div3" class="top-block">
</div>
</div>
</div>
</body>
</html>
Upvotes: 1
Views: 578
Reputation: 229
Apply below code
.pretty-button
{
color: white;
background-color: rgba(17, 175, 29, 0.64);
border-radius: 0.6em;
border: 0.2em solid #73AD21;
padding: 0.5em;
display: flex;
margin: auto;
z-index: 9;
position: relative;
}
.top-block
{
position: absolute;
top: 0px;
height: 60px;
width: 60%;
margin: auto;
background-color: purple;
z-index: +1;
left: 0;
right: 0;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="pretty-button">Button A</button>
<div id="div1">
<div id="div2">
<div id="div3" class="top-block">
</div>
</div>
</div>
</body>
</html>
Upvotes: 0
Reputation: 678
This should help in centering the div horizontally!
<!DOCTYPE html>
<html>
<head>
<style>
.pretty-button {
color: white;
background-color: rgba(17, 175, 29, 0.64);
border-radius: 0.6em;
border: 0.2em solid #73AD21;
padding: 0.5em;
}
.top-block {
position: absolute;
top: 0px;
height: 30px;
width: 60%;
background-color: purple;
left: 20%;
}
</style>
</head>
<body>
<button class="pretty-button">Button A</button>
<div id="div1">
<div id="div2">
<div id="div3" class="top-block">
</div>
</div>
</div>
</body>
</html>
Upvotes: 0
Reputation: 133
Just add this: transform: translateX(35%);
and z-index: 999
to your .top-block
class
Upvotes: 0
Reputation: 4364
apply below code z-index: 9999; margin-left: 20%;
.top-block {
position: absolute;
top: 0px;
height: 30px;
width: 60%;
margin: auto;
background-color: purple;
z-index: 9999;
margin-left: 20%;
}
Upvotes: 1