Reputation: 85
I'm trying to align a span
element in the center of a container div
, and have another span
with right-aligned text aligned left of it:
+--------------------------------------------------------+
| <div> |
+----------------------+----------+ |
| <span> | <span> | |
| | | |
| | | |
| | | |
| right-aligned | centered | |
| | | |
| | | |
| | | |
| | | |
+----------------------+----------+ |
| |
+--------------------------------------------------------+
The contents of both spans are dynamically generated, so I'd like to avoid any absolute pixel widths if possible.
Any idea how to achieve this type of layout?
Here is the markup I eventually went with based on Persinj's answer:
HTML
<nav class="navbar">
<span class="nav-aside">Right-aligned: </span>
<span class="nav-menu">centered</span>
<span class="nav-aside"></span>
</nav>
CSS
nav.navbar {
display: flex;
}
span.nav-aside {
flex-grow: 1;
flex-basis: 0;
text-align: right;
}
span.nav-menu {
align-self: center;
text-align: center;
}
I left the vendor prefixes out of my markup since I have limited browser requirements, and I'm relying on autoprefixer to take care of that. Please see the accepted answer if you need them.
Upvotes: 1
Views: 3004
Reputation: 14990
This can be sloved using flex:
Setting tree boxes:
Aside, center and a hidden one, will fill the required space.
Setting a flex-grow
will make make them take up different parts of the page.
Setting flex-grow: 1;
on each will make them take up equal space.
Setting one of them to flex-grow: 0.5
; will give this part less space to grow.
Adding a wrapper with the flex property we can use align-items:center
to make sure they stay in the center of the wrapper.
.wrapper {
height: 250px;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
flex-wrap: nowrap;
flex-direction: row;
align-items: center;
text-align: center;
}
.center,
.aside,
.not-shown {
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
.center {
flex-grow: 0.5;
background-color: lightblue;
height: 50px;
}
.aside {
text-align: right;
background-color: 1;
background: lightgreen;
height: 50px;
}
.not-shown {
visibility: hidden;
flex-grow: 1.5;
height: 50px;
}
<div class="wrapper">
<div class="aside">
aside
</div>
<div class="center">
center
</div>
<div class="not-shown">
</div>
</div>
Upvotes: 2
Reputation: 196
HTML:
<div class="wrapper">
<span class="span-left">right-aligned</span>
<span class="span-center">centered</span>
</div>
CSS:
.span-left, .span-center { display: inline-block; }
.span-left {
width: 40%;
text-align: right;
}
.span-center {
width: 20%;
text-align: center;
}
Alternatively, use display: block
and float: left;
on your spans (don't forget to clear after the wrapper).
Upvotes: 1