垂直和水平居中文本,无需绝对定位
Center text vertically and horizontally without absolute positioning
首先,它与其他问题不同因为我不能使用我通常使用的position: absolute;
因为我的jQuery插件(我示例中不要使用这个插件,但是我必须对里面做position: relative;
-table).
JSFIDDLE:https://jsfiddle.net/h8ywumbk/
HTML:
<div id="table">
<div id="inside-table" >
<span>Hello</span>
</div>
</div>
CSS:
#table {
width: 100%;
height: 100px;
border: solid 1px black;
background-color: transparent;
}
#inside-table {
position: relative;
width: 98%;
height: 80px;
background-color: transparent;
border: solid 1px black;
margin: 0 auto;
margin-top: 10px;
}
#inside-table span {
position: relative;
top: 50%;
transform: translateY(-50%);
}
我试图将文本(不是单行)在 table 上垂直和水平居中。有什么建议吗?
只需使用flexbox
#table {
width: 100%;
height: 100px;
border: solid 1px black;
background-color: transparent;
}
#inside-table {
position: relative;
width: 98%;
height: 80px;
background-color: transparent;
border: solid 1px black;
margin: 0 auto;
margin-top: 10px;
display: flex;
justify-content: center;
align-items: center;
}
#inside-table span {
}
<div id="table">
<div id="inside-table">
<span>Hello</span>
</div>
</div>
试试这个:
.table {
display: table;
width: 100%;
}
.td {
display: table-cell;
vertical-align: middle;
}
<div class="table">
<div class="td">
text
</div>
<div class="td">
<img alt="" src="http://url style="width: 120px; height: 148px;" />
</div>
</div>
我是这样居中的:
#inside-table span {
position: relative;
top: 50%;
left: 50%;
}
如果你想让它向一个方向或另一个方向移动,你总是可以弄乱百分比
首先,它与其他问题不同因为我不能使用我通常使用的position: absolute;
因为我的jQuery插件(我示例中不要使用这个插件,但是我必须对里面做position: relative;
-table).
JSFIDDLE:https://jsfiddle.net/h8ywumbk/
HTML:
<div id="table">
<div id="inside-table" >
<span>Hello</span>
</div>
</div>
CSS:
#table {
width: 100%;
height: 100px;
border: solid 1px black;
background-color: transparent;
}
#inside-table {
position: relative;
width: 98%;
height: 80px;
background-color: transparent;
border: solid 1px black;
margin: 0 auto;
margin-top: 10px;
}
#inside-table span {
position: relative;
top: 50%;
transform: translateY(-50%);
}
我试图将文本(不是单行)在 table 上垂直和水平居中。有什么建议吗?
只需使用flexbox
#table {
width: 100%;
height: 100px;
border: solid 1px black;
background-color: transparent;
}
#inside-table {
position: relative;
width: 98%;
height: 80px;
background-color: transparent;
border: solid 1px black;
margin: 0 auto;
margin-top: 10px;
display: flex;
justify-content: center;
align-items: center;
}
#inside-table span {
}
<div id="table">
<div id="inside-table">
<span>Hello</span>
</div>
</div>
试试这个:
.table {
display: table;
width: 100%;
}
.td {
display: table-cell;
vertical-align: middle;
}
<div class="table">
<div class="td">
text
</div>
<div class="td">
<img alt="" src="http://url style="width: 120px; height: 148px;" />
</div>
</div>
我是这样居中的:
#inside-table span {
position: relative;
top: 50%;
left: 50%;
}
如果你想让它向一个方向或另一个方向移动,你总是可以弄乱百分比