问题
How can I pin Menu
to the left edge of the viewport, while keeping My Awesome Site
horizontally centered (relative to the viewport)? align-items: center
and justify-content: center
are just starting points... I don't know if I need to use a combination of other Flexbox rules.
Requirements:
- Use Flexbox.
- Don't add any more HTML.
- Keep the CSS as clean as possible.
Notes:
align-items: center
andjustify-content: center
are just guesses... I'm cool with other Flexbox combinations.
header {
display: flex;
align-items: center;
justify-content: center;
}
a {
background-color: beige;
}
h1 {
background-color: yellow;
}
<header>
<a>Menu</a>
<h1>My Awesome Site</h1>
</header>
回答1:
The most simple and efficient that comes to mind is using position: absolute
, though based on other requirements it might need another solution
header {
display: flex;
align-items: center;
justify-content: center;
}
a {
position: absolute;
left: 0;
background-color: beige;
}
h1 {
background-color: yellow;
}
<header>
<a>Menu</a>
<h1>My Awesome Site</h1>
</header>
If you can give the "Menu" a fixed width, you can do this,
header {
display: flex;
align-items: center;
justify-content: center;
}
a {
width: 80px;
margin-right: -80px;
background-color: beige;
}
h1 {
margin: 0 auto;
background-color: yellow;
}
<header>
<a>Menu</a>
<h1>My Awesome Site</h1>
</header>
or this.
header {
display: flex;
align-items: center;
justify-content: center;
}
a {
width: 80px;
background-color: beige;
}
h1 {
flex: 1;
margin-right: 80px;
background-color: yellow;
text-align: center;
}
<header>
<a>Menu</a>
<h1>My Awesome Site</h1>
</header>
回答2:
This is my solution. I haven't added more HTML but I just used the semantic naming.
<!DOCTYPE html>
<html lang="en-GB">
<head>
<title>My Awesome Site</title>
<style>
html, body {
padding: 0; margin: 0;
}
.my-awesome-flex-container {
display: flex;
}
.my-awesome-flex-item {
padding: 1em;
flex-grow: 1;
}
.my-awesome-menu {
background-color: #3d94a6;
}
.my-awesome-site {
background-color: #c8c8c3;
text-align: center;
flex-grow: 6;
}
</style>
</head>
<body>
<header class="my-awesome-flex-container">
<nav class="my-awesome-flex-item my-awesome-menu">
Menu
</nav>
<section class="my-awesome-flex-item my-awesome-site">
My Awesome Site
</section>
</header>
</body>
</html>
回答3:
Setting margin-left
and right
to auto
, you can align the second element in the center.
header {
display: flex;
align-items: center;
justify-content: flex-start;
}
a {
background-color: beige;
}
h1 {
background-color: yellow;
margin-left: auto;
margin-right: auto;
}
<header>
<a>Menu</a>
<h1>My Awesome Site</h1>
</header>
来源:https://stackoverflow.com/questions/41403326/how-can-i-pin-one-node-to-left-viewport-edge-while-keeping-other-node-horizon