用CSS将中心内容对齐

问题描述

我正在尝试创建一个外观相似的google搜索,并且尝试将内容排列在中心时,我将它们相互叠加。有没有办法让它们以安排好的格式逐滴放置?

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Search</title>
        <Meta name="viewport" content="width=device-width,initial-scale=1">
        <link rel="stylesheet" href="style.css">
        <style> 
            .center {
 
               height: 100vh;
               position: relative;
    
            } 

           .center > div {
                margin: 0;
                position: absolute;
                top: 50%;
                left: 50%;
                margin-right: -50%;
                transform: translate(-50%,-50%) 
                }
         <style>

    </head>
    <body>
        <div class="container">
            <div class="links">
                <a href="googleImageSearch.html">Google Image Search</a>
                <a href="gooleAdvancedSearch.html">Google Advanced Search</a>
            </div>
            <br>
            <div class="center">
                <div class="logo">
                    <img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt="Google" width="272" height="92">
                </div>
                <br>
                <div>
                    <form action="https://google.com/search">
                        <input type="text" name="q">
                        <div class="buttons">
                            <input type="submit" value="Google Search">
                            <input type="button" value="I'm Feeling Lucky">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

解决方法

尝试使用flexboxalign-itemsjustify-content属性将使您可以在中心对齐内容。然后,您将不得不对其他元素进行一些小的调整。

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  flex-direction: column;
  width: 100vw;
} 


form {
  diplay: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

input[type="text"] {
  border-radius: 2.5em;
  height: 2em;
  width: 500px;
  border: 1px solid black;
}

.buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 1em;
}

.buttons > * {
  margin-right: 0.85em;
}
,

我建议你:

.center{
   margin:0 auto;
 }

如果您要在div和页面顶部之间留出更多空间,则应将div居中在页面中心 现在,我看到您嵌套了具有不同样式的div,因此将margin:0自动;在容器类中将所有元素居中,并删除相对位置。或在“中心”类中将其全部删除并替换为我的代码