到目前为止,我一直在尝试创建此图中所示的基本网站布局。 https://imgur.com/a/JhURder
它包括一个灰色背景,里面有一个居中的div,白色背景。图像居中位于左侧,文本等位于右侧。
我是Twitter引导程序的拥护者,到目前为止,我已经实现了这一点。 (反应样式)
<div class="container-fluid" style={{
'background-color' : 'rgb(224,225,226)',
'height' : '40vh'
}}>
<div class="row">
<div class="col-1 text-center"> Test </div>
<div class="col-10 text-center" style={{
'height' : '30vh',
'background-color' : 'rgb(255,255,255)',
'margin-top' : '5vh'
}}>
centered
</div>
<div class="col-1 text-center">test</div>
</div>
</div>
到目前为止,已经成功了一半。但说实话,我有点给了我们,因为它变成了嵌套的混乱。通过网站开发,我一直知道他们是一个更大的方法,因此我到这里来是为了让人们ast跃尝试,并可以以适当的方式实现我的目标。
答案 0 :(得分:1)
以下是一些有关如何实现它的想法。
https://codepen.io/Warisara-L/pen/wOMxwR
// HTML
<div class="wrapper" id="solution-1">
<div class="inner">1</div>
</div>
// SCSS
#solution-1 {
display: grid;
.inner {
margin: auto;
}
}
#solution-2 {
display:flex;
justify-content: center;
align-items: center;
}
#solution-3 {
position: relative;
.inner {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
}
#solution-4 {
display: flex;
.inner {
margin: auto;
}
}
#solution-5 {
display: grid;
justify-content: center;
align-items: center;
}
#solution-6 {
position: relative;
.inner {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
}
#solution-7 {
height: 120px;
line-height: 120px;
text-align: center;
.inner {
display: inline-block;
vertical-align: middle;
}
}
#solution-8 {
display: flex;
.inner {
align-self: center;
margin: 0 auto;
}
}
先生,祝您有美好的一天
答案 1 :(得分:0)
使用display: flex;
,您可以将justify-content
和align-items
的属性指定为center
,以使子元素在水平和垂直方向上居中。
当display: flex
元素是一行(flex-direction: row;
)时,justify-content
将处理水平位置,而align-items
将处理垂直位置。将flex-direction
设置为column
时,将交换justify-content
和align-items
的含义。
示例:
.parent-element {
display: flex;
/* flex-direction defaults to row */
justify-content: center;
align-items: center;
}
您可以利用属性place-items
使网格的子级居中。但是,您应该注意,目前并非所有浏览器都支持place-items
。
示例:
.parent-element {
display: grid;
place-items: center;
}
有时候,您可以利用auto
属性的margin
值将元素推向中心。
请务必查看这篇说明what is needed for margin: auto;
to work的帖子。
示例:
.child-element {
/* top right bottom left -- all set to auto */
margin: auto;
}
您可以通过将position
属性设置为absolute
(将其从普通文档流中删除),将一个项目放置在屏幕中央。然后,您可以使用属性left
和top
将元素向下和向右移50%
。
一旦将其推入50%
,我们需要将其移回元素宽度/高度的一半,我们可以在属性translate
内使用transform
来实现。
示例:
.child-element {
position: absolute;
top: 50%;
left: 50%;
/* translate(<x value>, <y value>) */
transform: translate(-50%, -50%);
}
不建议您将这些元素作为普通文档流的一部分,因为它们很可能与其他元素重叠。但这对模态很有用。
答案 2 :(得分:-1)
尝试在要居中的内部div中设置css margin: 0 auto
。