当使用页眉时,尝试使用display:flex将文本集中在主页上



我正在尝试使用display:flex将网页上的文本置于中间偏右的位置,同时我插入了一个带有徽标的页眉。我使用以下代码成功地做到了这一点:

方法1

position: absolute
top: 50%
left: 50%
transform: translate(-50%, -50%)

结果如下:https://codepen.io/pen/QWKrrNq

然而,当我尝试使用display:flex实现这一点时,使用以下代码:

方法2

height: 100%    
display: flex
justify-content: center
align-items: center
flex-direction: column

结果如下:https://codepen.io/pen/wvzjjMJ

正如您在方法1中看到的那样,文本完全居中,而在方法2中则不是。

我知道这是因为页眉占据的高度,这会影响居中文本的div所使用的空间。然而,我只想知道是否有可能通过display flex实现方法1中所做的事情?

我曾尝试将文本容器div的高度从100%更改为80%、70%等……这在最初似乎有效,但当视口宽度更改时,文本会偏离中心,这与方法1不同。我唯一能想到的避免这种情况的方法是对不同高度的%s使用媒体查询。

使用display还有其他更简单的方法吗:flex?

感谢

通过使用flex,您可以通过以下代码制作中心

height: 100%;
display: flex;
align-items: center;
flex-direction: column;
margin-top: 50px;

删除对齐内容中心,并将页边空白或填充顶部添加到div

我认为处理这一问题的最简单方法是对header_nav元素使用绝对定位,类似于您的第一个示例。header_text元素将不再相对于导航定位,导航将固定在页面顶部(可能是您想要的位置(

在第二个示例中,添加定位规则:

&__nav
display: flex
padding: 1rem
position: absolute

为我居中显示标题文本。

它没有完全居中的原因是header__nav占用了空间。然后把东西往下推。

你必须想知道你想要什么。导航是否总是在顶部,就像位置:绝对?如果那没问题的话。下面的代码起作用,并以标题为中心。

*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: inherit;
}
html {
font-size: 62.5%;
}
body {
box-sizing: border-box;
line-height: 1.7;
color: white;
padding: 1rem;
font-family: "Andika New Basic", sans-serif;
}
.container {
margin: 0 auto;
position: relative;
}
.header {
height: 95vh;
background-image: linear-gradient(to right top, #7cc071c0, #168042a2), url(../img/hero.jpg);
background-size: cover;
background-position: top;
background-repeat: no-repeat;
clip-path: polygon(0 0, 100% 0, 100% 80%, 0% 100%);
}
.header__nav {
display: flex;
padding: 1rem;
position: absolute;
top: 0;
right: 0;
left: 0;
}
.header__nav--logo {
max-width: 15%;
}
.header__text {
height: 100%;
display: flex;
text-align: center;
justify-content: center;
align-items: center;
flex-direction: column;
}
.header__text--title {
letter-spacing: 1rem;
text-transform: uppercase;
font-size: 2.5rem;
}
.header__text--copy {
letter-spacing: 0.3rem;
margin-top: 2rem;
font-size: 1.6rem;
}
<body>
<section class="container">
<header class="header">
<div class="header__nav">
<img class="header__nav--logo" src="https://github.com/jonasschmedtmann/advanced-css-course/blob/master/Natours/starter/img/logo-white.png">
</div>
<div class="header__text">
<h1 class="header__text--title">
Welcome to my website
</h1>
<h2 class="header__text--copy">
Click the buttons below to enter
</h2>
</div>
</header>
</section>
</body>

最新更新