我有以下代码段:
.float-left {
float: left !important;
}
.float-right {
float: right !important;
}
.container {
padding: 1rem;
}
.clearfix {
clear: both;
}
.has-border {
border: 2px solid #000;
}
.d-inline-block {
display: inline-block !important;
}
.align-middle {
vertical-align: middle !important;
}
<div class="has-border">
<div class="container">
<div class="div1 float-left">
Contact
</div>
<div class="div2 float-right">
<button class="d-inline-block">
Hey
</button>
<svg width="20" height="20">
<circle cx="10" cy="10" r="40"
stroke="green" stroke-width="4" fill="yellow" />
Sorry, your browser does not support inline SVG.
</svg>
</div>
<div class="clearfix"></div>
</div>
</div>
如您所见,按钮和svg并排,但未垂直对齐。
那么,我该如何将同时完美对齐的svg和按钮并排放置?
答案 0 :(得分:2)
我使用flexbox来对齐项目并稍微整理一下代码。
.container {
padding: 1rem;
display: flex;
align-items: center; /* vertical alignment */
}
.has-border {
border: 2px solid #000;
}
.div2 {
margin-left: auto; /* Pushes it to the right */
display: flex;
align-items: center; /* vertical alignment */
}
<div class="has-border">
<div class="container">
<div class="div1">
Contact
</div>
<div class="div2">
<button>
Hey
</button>
<svg width="20" height="20">
<circle cx="10" cy="10" r="40"
stroke="green" stroke-width="4" fill="yellow" />
Sorry, your browser does not support inline SVG.
</svg>
</div>
</div>
</div>
答案 1 :(得分:2)
删除float-left
和clearfix
类,并将display: flex;
添加到.float-right
,将display: flex; align-items:center;
添加到.container
.float-right {
margin-left: auto;
display: flex;
}
.container {
padding: 1rem;
display: flex;
align-items: center;
}
.has-border {
border: 2px solid #000;
}
.d-inline-block {
display: inline-block !important;
}
<div class="has-border">
<div class="container">
<div class="div1">
Contact
</div>
<div class="div2 float-right">
<button class="d-inline-block">
Hey
</button>
<svg width="20" height="20">
<circle cx="10" cy="10" r="40"
stroke="green" stroke-width="4" fill="yellow" />
Sorry, your browser does not support inline SVG.
</svg>
</div>
</div>
</div>
答案 2 :(得分:1)
将display:flex;
和align-items:center;
用于.float-right类,如下所示:
.float-right {
float: right;
display:flex;
align-items:center;
}
.float-left {
float: left;
}
.float-right {
float: right;
display:flex;
align-items:center;
}
.container {
padding: 1rem;
}
.clearfix {
clear: both;
}
.has-border {
border: 2px solid #000;
}
.d-inline-block {
display: inline-block;
}
.align-middle {
vertical-align: middle;
}
<div class="has-border">
<div class="container">
<div class="div1 float-left">
Contact
</div>
<div class="div2 float-right">
<button class="d-inline-block">
Hey
</button>
<svg width="20" height="20">
<circle cx="10" cy="10" r="40"
stroke="green" stroke-width="4" fill="yellow" />
Sorry, your browser does not support inline SVG.
</svg>
</div>
<div class="clearfix"></div>
</div>
</div>
注意:同样也不需要使用!important
答案 3 :(得分:0)
将此添加到按钮的CSS:
vertical-align: middle;
然后转到svg:
display: inline-block;
vertical-align: middle;