Issue
I'm trying to create a header for a page that puts the title of the page in the middle and centered absolutely. I tried to do this with flex box and justify-content:space-between
However as shown below I get the title skewed depending on the buttons width on the right (I've exaggerated that to show the effect)
While I was able to absolutely center the title (using absolute positioning on the h1) as in the example of "Want", a strange side-effect shows up on the buttons- they aren't clickable anymore! I'm flummoxed. What's going on here? How do I center the title and still keep the buttons working (with flex)?
<!DOCTYPE html>
<html>
<head>
<style>
body {
max-width: 32em;
margin: 0 auto;
}
nav {
display: flex;
flex-direction: row;
align-items: center;
width: 100%;
height: 2em;
justify-content: space-between;
border-bottom: 1px solid gray;
margin: 20px auto;
}
/* My attempt at keeping h1 absolutely centered on the page width */
h1.want {
left: 0;
position: absolute;
right: 0;
text-align: center;
top: 20px;
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<header>
<nav>
<div>
<button>Foo</button>
</div>
<div>
<div>
<h1 class="want">Want</h1>
</div>
</div>
<div>
<button>Bar</button>
<button>Bas</button>
<button>Bat</button>
<button>Bau</button>
</div>
</nav>
The buttons don't work here!
<nav>
<div>
<button>Foo</button>
</div>
<div>
<div>
<h1>Got this</h1>
</div>
</div>
<div>
<button>Bar</button>
<button>Bas</button>
<button>Bat</button>
<button>Bau</button>
</div>
</nav>
Buttons work here.
</header>
</body>
</html>
Solution
As mentioned user:Phix, problem is your headline (with position: absolute; property) overlay button. In this case you should add z-index to sibling node.
.button-wrapper {
z-index: 1;
}
<!DOCTYPE html>
<html>
<head>
<style>
body {
max-width: 32em;
margin: 0 auto;
}
nav {
display: flex;
flex-direction: row;
align-items: center;
width: 100%;
height: 2em;
justify-content: space-between;
border-bottom: 1px solid gray;
margin: 20px auto;
}
/* My attempt at keeping h1 absolutely centered on the page width */
h1.want {
left: 0;
position: absolute;
right: 0;
text-align: center;
top: 20px;
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<header>
<nav>
<div class="button-wrapper">
<button>Foo</button>
</div>
<div>
<div>
<h1 class="want">Want</h1>
</div>
</div>
<div>
<button>Bar</button>
<button>Bas</button>
<button>Bat</button>
<button>Bau</button>
</div>
</nav>
The buttons don't work here!
<nav>
<div>
<button>Foo</button>
</div>
<div>
<div>
<h1>Got this</h1>
</div>
</div>
<div>
<button>Bar</button>
<button>Bas</button>
<button>Bat</button>
<button>Bau</button>
</div>
</nav>
Buttons work here.
</header>
</body>
</html>
Answered By - Yaroslav Trach
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.