2017-04-07 81 views
0

那么,通常当我需要对齐框旁边的文本,我这样做: https://codepen.io/Maartinshh/pen/yMdNrW,但我听说它使用 填充和边距这种工作的可怕的错误。有其他选择吗?将文本对齐到另一个元素的最佳方法?

<div class="box"></div> 
<div class="text">Text</div> 

.box{ 
    background-color:blue; 
    width: 70px; 
    height: 70px; 
} 

.text{ 
    padding-left: 80px; 
    margin-top: -40px; 
} 
+0

使用inline-block的+垂直对齐:中间两个DIV –

回答

1

对于你的榜样,我会改变显示类型inline-block,然后用vertical-align属性来居中文本。

.box { 
 
    background-color: blue; 
 
    width: 70px; 
 
    height: 70px; 
 
    display: inline-block; 
 
    vertical-align: middle; 
 
} 
 

 
.text { 
 
    display: inline-block; 
 
    vertical-align: middle; 
 
}
<div class="box"></div> 
 
<div class="text">Text</div>

第二种方法可能会使用flexbox。你可以用一个容器div的都和应用弯曲特性吧:

.wrap { 
 
    display: flex; 
 
    align-items: center; 
 
} 
 

 
.box { 
 
    background-color: blue; 
 
    width: 70px; 
 
    height: 70px; 
 
}
<div class="wrap"> 
 
    <div class="box"></div> 
 
    <div class="text">Text</div> 
 
</div>

+0

好了,但如果在你的版本但从“更好的代码”点有什么区别? – Poo123

+0

考虑响应性时,使用填充和具有固定值的边距很尴尬。这也意味着,如果您更改div的大小,甚至字体大小,则需要更新其他值 – sol

0

使用可以使用inline-block的和垂直对齐。

.box{ 
    background-color:blue; 
    width: 70px; 
    height: 70px; 
    display: inline-block; 
    vertical-align: middle; 
} 

.text{ 
    padding-left: 10px; 
    display: inline-block; 
    vertical-align: middle; 
} 
相关问题